Java JUnit测试以获得更多的2个值?

Java JUnit测试以获得更多的2个值?,java,junit,assertions,Java,Junit,Assertions,我需要一些帮助,弄清楚如何获得2个较大值的JUnit测试 我知道如何对简单函数(如加法、减法等)进行Junit测试,但不会找到两者中更大的值 这就是我所拥有的: public static int getMax(int x, int y){ if(x >= y) { return x; } else { return y; } } 我一直在验证我写的东西。在进行单元测

我需要一些帮助,弄清楚如何获得2个较大值的JUnit测试

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

这就是我所拥有的:

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

我一直在验证我写的东西。

在进行单元测试时,你所做的就是调用函数并比较它的性能 测试的结果应该和您已经做的一样

使用JUnit4

@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) );
    }
}

从检查准则来看,只有一个分支机构,因此只涉及两种情况:

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

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

我会:

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);
  }

}

您应该考虑测试用例。。x=y,xy,使用负数,使用0,使用正数。我不明白你的问题。如果getMax方法等于或大于y,则返回x,否则将返回y。这不是单元或JUnit测试。如果这是您编写单元测试的方法,那么单元测试方法应该类似于:@test public void testGetMax()…当
i==j
时,您的
complextTestCase
是错误的。我还建议在使用随机数生成器之前,如果I>j和I==j作为单独的测试来测试其他两个通用用例,因为如果有错误(如这里),我们可能会暂时没有注意到,然后在测试突然失败时会感到困惑。如果I==j,那么I和j都是最大值。
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);
  }

}