0

我需要一些帮助来弄清楚如何获得更大数量的 2 个值的 JUnit 测试。

我知道如何对简单函数(如加法、减法等)进行 Junit 测试,但没有找到两者中更大的值。

这就是我所拥有的:

 public static int getMax(int x, int y){
        if(x >= y) {
            return x;
        }
        else {
            return y;
        }
    }

我坚持证明我写的东西。

4

3 回答 3

0

我会做:

import static org.assertj.core.api.Assertions.assertThat;
import org.junit.runner.RunWith;
import com.googlecode.zohhak.api.TestWith;
import com.googlecode.zohhak.api.runners.ZohhakRunner;

@RunWith(ZohhakRunner)
class MyMaxTest {

  @TestWith({
     "1, 2, 2",
     "2, 1, 2",
     "1, 1, 1"
  })
  public void shouldReturnMaximum(int number1, int number1, int expected) {

    int result = MyClass.getMax(number1, number2);

    assertThat(result).isEqualTo(expected);
  }

}
于 2013-10-13T19:11:25.413 回答
0

通过检查代码,只有一个分支,因此只涉及两种情况:

@Test
public void firstNumberGreaterThanSecondIsReturned()
{
    assertEquals(1, NumericUtils.getMax(1, 0));
}

和:

@Test
public void secondNumberGreaterThanFirstIsReturned()
{
    assertEquals(1, NumericUtils.getMax(0, 1));
}

如果您将其编写为 TDD,您可能会从相等的数字或其他边界情况开始,但除非还有其他情况您不确定,否则添加更多测试是不值得的。

于 2013-10-08T11:51:49.927 回答
0

在进行单元测试时,您正在调用该函数并将其结果与您期望的测试结果进行比较,这与您已经完成的应该没有什么不同。

使用junit 4

@Test public void mySimpleTestCase(){
    // assertEquals tells junit you want the two values to be equal
    // first parameter is your expected result second is the actual result
    assertEquals(2 , MyFunctions.getMax(1,2) );
}

@Test public void myComplexTestCase(){
    // by generating numbers randomly we can do a slightly 
    // different test each time we run it.
    Random r = new Random();
    int i = r.nextInt();
    int j = r.nextInt();
    if (i > j){
      assertEquals("looking for max of " +i + " : " + j, i , MyFunctions.getMax(i,j) );
    } else {
      assertEquals("looking for max of " +i + " : " + j, j , MyFunctions.getMax(i,j) );
    }
}
于 2013-10-02T03:37:52.043 回答