java - 如何使用 J-unit 测试简单的 if else 语句?

标签 java testing white-box

我有这个 if-else 语句,我想编写一个 J 单元测试来测试每一行以查看是否正确。有什么想法吗?

public class Testings {

    public static int computeValue(int x, int y, int z) {
        int value = 0;

        if ( x == y ) 
            value = x + 1;
        else if (( x > y) && ( z == 0))
            value = y + 2;
        else
            value = z;

        return value;
    }
}

最佳答案

使用涵盖所有情况的值测试您的方法:

  • x == y
  • x != y and x > y and z == 0
  • x != y and x > y and z != 0
  • x != y and x < y and z == 0
  • x != y and x < y and z != 0
  • x == y 和 z != 0
  • x == y 和 z == 0

例子:

assertEquals(4, Testings.computeValue(3, 3, 10)); // x == y
assertEquals(7, Testings.computeValue(10, 5, 0)); // x != y and x > y and z == 0
assertEquals(1, Testings.computeValue(10, 5, 1)); // x != y and x > y and z != 0
...

此外,每个测试方法都应该有一个断言,这样您就可以给它一个合适的名称:

@Test
public void testXEqualY(){
    int x=3, y=3, z=10;
    assertEquals(4, Testings.computeValue(x, y, z));
}

关于java - 如何使用 J-unit 测试简单的 if else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41340467/

相关文章:

java - 如何更改 CA SDM 中变更单的子工作流的状态?

java - 避免验证/提交 p :selectOneListbox's value completely

java - 用 Java 实现一个简单的 HTTPS 代理应用程序?

testing - 覆盖不完整的测试方法和模型是什么?

java - 为什么 Whitebox 无法识别我的私有(private)方法?

java - Spring Boot 测试始终运行 schema-${platform}.sql

java - org.openqa.selenium.ElementNotVisibleException : Element is not currently visible and so may not be interacted with Command duration or timeout:

java - 通过(伪)直接调用该处理程序方法来测试 Spring Controller - 好还是坏?如何实现?

testing - JUnit 是黑盒测试还是白盒测试?

testing - 单靠黑盒测试能否捕捉到白盒测试捕捉到的所有错误?