Is the statement the wrong tearDown (@After) method?

I have several test cases, even if the logic is different, the output should be the same on all of them. So I thought about how to generalize them and put the Assert method only once.

Is there a way to do this better than this:

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() {
    }
}

Launch method:

@Test
public void runTests() {
    Result result = JUnitCore.runClasses(Tests.class);
    assertThat(result.getRunCount(), is(2));
    assertThat(result.getFailureCount(), is(0));
}
+5
source share
2 answers

Yes, the statement in the tearDown method is a bad idea. This method exists, according to the JUnit documentation, for

Resets the lamp, for example, closes the network connection. This method is called after the test is completed.

, . , . :

public class FooTest {

    @Test
    public void testFoo() {
        Object expected = // ...
        Object actual = // ...

        assertThat(actual, is(equalsTo(expected)));
    }

}

, , . , , . , . , , , .

+7

, ,

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

.

, , .

+4

All Articles