gpt4 book ai didi

java - tearDown (@After) 方法断言错误吗?

转载 作者:搜寻专家 更新时间:2023-10-31 08:30:00 27 4
gpt4 key购买 nike

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

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

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 文档,此方法存在于

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

我认为将您的期望值和实际值存储在测试类中通常不是一个好主意。这些变量是测试相关的,因此将它们存储在您的测试用例中并在测试用例中进行断言。例如:

public class FooTest {

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

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

}

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

关于java - tearDown (@After) 方法断言错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3707544/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com