在tearDown(@After)方法上断言是错误的吗? [英] Is Assert-ing on tearDown (@After) method wrong?

查看:421
本文介绍了在tearDown(@After)方法上断言是错误的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我甚至有多个测试用例,如果逻辑不同,输出必须在所有测试用例上相等。所以我在考虑如何概括它们并仅将Assert方法放置一次。

I have multiple test cases even and if the logic is different, the output must be equal on all of them. So I was thinking in how to generalize them and place the Assert method only once.

有没有比这更好的方法:

Is there any way better to do it than this one:

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


推荐答案

是的,在tearDown中断言方法是个坏主意。根据JUnit文档,此方法存在于

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


拆除夹具,例如,关闭网络连接。在执行测试后调用此方法。

Tears down the fixture, for example, close a network connection. This method is called after a test is executed.

我认为将预期值和实际值存储在测试类中是一个坏主意一般来说。这些变量与测试有关,因此将它们存储在测试用例中并在测试用例中执行断言。例如:

I think that storing your expected and actual values in the test class are a bad idea in general. These variables are test-dependent, so store them inside your test case and do your assert in the test case. For example:

public class FooTest {

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

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

}

另外,我在你的代码中看到所有测试都具有相同的预期值。改变测试可能是个好主意,因此返回的值总是不同的。一直只测试一个预期值会确保代码适用于此预期结果。尝试更多,可能非常不同,并尝试测试一些极端情况。

Also, I see in your code that all test have the same expected value. It might be a good idea to vary your tests so returned values are always different. Testing only one expected value all the time make you sure the code works for this expected result. Try with some more, possibly very different, and try to test some corner cases.

这篇关于在tearDown(@After)方法上断言是错误的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆