代码之家  ›  专栏  ›  技术社区  ›  Alexander

在TearDown(@After)方法上断言是否错误?

  •  5
  • Alexander  · 技术社区  · 15 年前

    我有多个测试用例,即使逻辑不同,所有测试用例的输出也必须相等。所以我在想如何推广它们,并且只放置断言方法一次。

    有没有比这个更好的方法:

    static public class Tests() {
    
        private static String expected = null;
        private String actual = null;
    
        @BeforeClass
        public static void setUpBeforeClass() throws Exception {
            expected = new String("My Desired Output");
        }
    
        @Before
        public void setUp() {
            actual = new String();
        }
    
        @Test
        public void test1() throws Exception {
            actual = ...
        }
    
        @Test
        public void test2() throws Exception {
            actual = ...
        }
    
        @After
        public void tearDown() throws Exception {
            assertThat(actual, is(equalTo(expected)));
        }
    
        @AfterClass
        public static void tearDownAfterClass() {
        }
    }
    

    运行方法:

    @Test
    public void runTests() {
        Result result = JUnitCore.runClasses(Tests.class);
        assertThat(result.getRunCount(), is(2));
        assertThat(result.getFailureCount(), is(0));
    }
    
    2 回复  |  直到 13 年前
        1
  •  7
  •   Vivien Barousse    15 年前

    public class FooTest {
    
        @Test
        public void testFoo() {
            Object expected = // ...
            Object actual = // ...
    
            assertThat(actual, is(equalsTo(expected)));
        }
    
    }
    

        2
  •  4
  •   Alexander    13 年前

    private void testIt ( String actual ) {
        assertThat(actual, is(equalTo(expected)));
    }