我为JUnit的测试下面的代码:这段代码如何在JAVA中为JUnit工作?
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class JUnitHelloWorld {
protected String s;
@Before
public void setup() {
s = "HELLO WORLD";
}
@Test
public void testHelloWorldSuccess() {
s = s.toLowerCase();
assertEquals("hello world", s);
}
// will fail even if testHelloWorldSuccess is called first
@Test
public void testHelloWorldFail() {
assertEquals("hello world", s);
}
}
现在,根据意见,为什么会在第二种方法失败,即使第一种方法是先叫什么名字?是不是第一种将s的值改为小写的方法?
事实上切换到@BeforeClass将获得提供行为,但随后这将是糟糕的测试实践:-P –
在这种情况下,它是坏的测试实践,因为执行的顺序很重要。我包括'@ BeforeClass',这样OP就可以理解如何从'@ Before'得到他们期待的行为。 – n00begon