JUnit 4测试用例

时间:2016-12-22 09:50:31

标签: java junit4 testcase

我需要帮助为此代码创建JUnit 4测试用例。

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

被修改

我想要这样的东西测试if else语句

public class TestingTest {

    @Test
        public void testComputeValueTCXX() {

        }

        …

    @Test
        public void testComputeValueTCXX() {

        }

        }

3 个答案:

答案 0 :(得分:5)

让你入门的东西......

首先是“扩展”版本,可能对“新手”更有帮助:

@Test
public void testXandYEqual() {
  // arrange
  int x=0;
  int y=0;
  int anyValueBeingIgnored=0;
  // act
  int result = ThatClass.computeValue(x, y, anyValueBeingIgnored);
  // assert
  assertThat(result, is(1));
}

以上测试了那些级联的ifs的第一个案例;其中assertThat是众多JUnit断言之一; is()是一种简单的匹配方法。此外,这就是我写这个测试用例的方式:

@Test
public void testXandYEqual() {
  assertThat(ThatClass.computeValue(0, 0, 1), is(1));
}

(主要区别在于:对我来说,单元测试不应包含任何我不需要的信息;在这个意义上:我希望它尽可能纯粹,简洁,简洁)

基本上,您希望编写不同的测试,以涵盖通过逻辑的所有路径。您可以使用众多现有coverage工具之一来确保覆盖所有路径。

或者,您也可以查看parameterized测试。含义:您可以将所有不同的“调用参数”放入;而不是创建大量的测试方法,而每个测试方法只使用不同的参数调用您的实际方法。然后JUnit从该表中获取所有数据,并在调用测试中的“目标”方法时使用它。

答案 1 :(得分:1)

像这样的东西。

    @Test
    public void testcomputeValueWithXYandZAsZero() {

        int result = YourClass.computeValue(0, 0, 0);

        Assert.assertEquals(1, result);
    }

确保使用不同的输入集编写测试用例,以便覆盖静态方法的所有分支。

您可以使用EclEmma等插件来检查测试的覆盖范围。 http://www.eclemma.org/

答案 2 :(得分:0)

假设您的测试方法位于Stackoverflow类中。您需要一个名为StackoverflowTest的测试类。这就是它的样子:

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author someAuthor
 */
public class StackoverflowTest {

    public StackoverflowTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    // TODO add test methods here.
    // The methods must be annotated with annotation @Test. For example:
    //
    // @Test
    // public void hello() {}

    // Here you test your method computeValue()
    // You cover all three cases in the computeValue method

    @Test
    public void computeValueTest() {
        assertTrue(3 == computeValue(2, 2, 0));
        assertTrue(4 == computeValue(3, 2, 0));
        assertTrue(200 == computeValue(1,2,200));
    }
}