我需要帮助为方法编写Junit 5测试

发布于 2025-02-11 08:04:28 字数 461 浏览 1 评论 0原文

我是Java的新手,我的任务是为已编写的代码创建JUNIT5测试。首先,我有以下方法需要为测试编写测试。我不确定如何对此方法进行测试。

public static double getFormattedDoubleValue(数字值){返回getFormattedDoubleValue(value,-1); }

我尝试了以下测试,它通过了,但是我觉得我在这里测试了错误的事情。

@Test
public void testDoubleString() {
    Double num = 41.1212121212;
    String expected = "41.12";
    String actual = String.format("%.2f", num);
    assertEquals(expected, actual, "Should return 41.12");}

I am very new to Java, and I have been tasked with creating Junit5 tests for already written code. To start, I have the below method that I need to write a test for. I am unsure how to approach a test for this method.

public static Double getFormattedDoubleValue(Number value){ return getFormattedDoubleValue(value, -1); }

I tried the below test, and it passes, but I feel like I am testing the wrong thing here.

@Test
public void testDoubleString() {
    Double num = 41.1212121212;
    String expected = "41.12";
    String actual = String.format("%.2f", num);
    assertEquals(expected, actual, "Should return 41.12");}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘东忘西忘不掉你 2025-02-18 08:04:28

写作测试比有时要简单,只是从测试类调用您的代码,而不是商务逻辑类,并确保根据输入的内容获得正确的输出。

这是一篇很棒的文章,它将带您从流程的一开始: baeldung:junit 5


可能的样本测试

因为我不确定您的方法的期望是什么,我只是假装您的方法应该服用double,然后返回该方法数字减一个:

@Test
void getFormattedDoubleValue_Test() {
    Double expected = 5.0L
    Double actual = getFormattedDoubleValue(expected + 1L)

    assertEquals(expected, actual)
}

Writing tests are simpler than they are sometimes made out to be, all it is is just calling your code from a test class instead of a business logic class and making sure that you get the right output based on what you input.

Here is an excellent article that will take you from the very beginning of the process: Baeldung: JUnit 5


Possible Sample Test

As I'm not quite certain what the expectations of your method are, I am just going to pretend that your method should take a Double, and return that number minus one:

@Test
void getFormattedDoubleValue_Test() {
    Double expected = 5.0L
    Double actual = getFormattedDoubleValue(expected + 1L)

    assertEquals(expected, actual)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文