有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaJUnit4测试用例

我需要关于为这段代码创建JUnit4测试用例的帮助

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) 个答案

  1. # 1 楼答案

    像这样的

        @Test
        public void testcomputeValueWithXYandZAsZero() {
    
            int result = YourClass.computeValue(0, 0, 0);
    
            Assert.assertEquals(1, result);
        }
    

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

    你可以使用像EclEmma这样的插件来检查测试的覆盖率。 http://www.eclemma.org/

  2. # 2 楼答案

    让你开始的东西

    首先是一个可能对“新手”更有用的“扩展”版本:

    @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()是一种hamcrest匹配方法。此外,以下是我编写测试用例的方式:

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

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

    基本上,你需要编写不同的测试,以覆盖贯穿逻辑的所有路径。您可以使用许多现有的coverage工具之一来确保覆盖所有路径

    或者,您也可以查看parameterized测试。意思是:不要创建很多测试方法,每个方法都只是用不同的参数调用实际方法,而是将所有这些不同的“调用参数”放入一个表中;然后JUnit从该表中获取所有数据,并在调用测试中的“target”方法时使用这些数据

  3. # 3 楼答案

    假设您要测试的方法位于类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));
        }
    }