JUnit测试以获得更大数量的2个值?

时间:2013-10-02 03:23:18

标签: java junit assertions

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

我知道如何对简单函数进行Junit测试,例如添加,减去等等,但没有找到更大的值。

这就是我所拥有的:

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

我坚持证明我所写的内容。

3 个答案:

答案 0 :(得分: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) );
    }
}

答案 1 :(得分:0)

从检查代码开始,只有一个分支,因此只涉及两个案例:

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

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

如果你把它写成TDD,你可能会从相同的数字或其他边界情况开始, 但除非有其他情况你不自信,否则添加更多测试是不值得的。

答案 2 :(得分: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);
  }

}