我不明白为什么test1()
与test2()
相同却失败了。而另一个测试方法却成功了...
assertTrue(str.equals("hello"));
会导致NPE。
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import junit.framework.TestCase;
class UnderTest {
private static UnderTest instance;
private ToMock toMock;
public void doSomething() {
String str = toMock.get();
assertTrue(str.equals("hello"));
}
public static UnderTest getInstance() {
if (instance == null) {
instance = new UnderTest();
}
return instance;
}
public void set(ToMock toMock) {
this.toMock = toMock;
}
public ToMock get() {
return toMock;
}
}
public class SomeTest extends TestCase {
private ToMock toMock;
private UnderTest underTest;
private String str;
public SomeTest() {
toMock = mock(ToMock.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
str = (String) args[0];
return null;
}
}).when(toMock).set((String) org.mockito.Mockito.any());
when(toMock.get()).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return str;
}
});
UnderTest.getInstance().set(toMock);
}
@Before
public void setUp() throws Exception {
// UnderTest.getInstance().set(toMock);
}
@After
public void tearDown() throws Exception {
}
@Test
public void test1() {
toMock.set("hello");
UnderTest.getInstance().doSomething();
}
@Test
public void test2() {
toMock.set("hello");
UnderTest.getInstance().doSomething();
}
}
下面的接口应该放在一个额外的文件中。否则,它将无法被Mockito模拟。
public interface ToMock {
void set(String str);
String get();
}
但是,一旦我取消注释:
@Before
public void setUp() throws Exception {
// UnderTest.getInstance().set(toMock);
}
两种方法都会成功。我不明白这个指令如何影响str
字段。看起来在test1()
和test2()
调用之间,str
被设置为null
。但是为什么?在我所知道的范围内,我不必调用setUp()
来保留某些字段的当前值。在JUnit中,SomeTest
的状态(包括str
)不应该在测试方法调用之间丢失。
这可以怎样解释呢?
junit.framework.TestCase
和org.junit.*
有何不同? - Sotirios Delimanolis