【发布时间】:2016-08-16 19:53:35
【问题描述】:
我不明白为什么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 字段。看起来str 在test1() 和test2() 的调用之间设置为null。但为什么和在哪里?据我所知,我不必仅仅为了保留某些字段的当前值而调用setUp()。 SomeTest(包括str)的状态不应在 JUnit 中的测试方法调用之间丢失。
如何解释?
【问题讨论】:
-
为什么要混淆 JUnit 版本?
junit.framework.TestCase和org.junit.*? -
@SotiriosDelimanolis 我只是将它限制在一个 - junit.framework.TestCase 具有相同的结果。
标签: java testing junit mocking mockito