【发布时间】:2018-11-25 07:36:42
【问题描述】:
我有以下包含成员变量的类,但 Mockito 似乎无法模拟成员变量的方法。以下是我的待测系统:
public class MessageConsumer {
private ConsumerResponse consumerResponse;
private NotificationConsumer notificationConsumer;
@Scheduled(cron = "${com.example.value}")
public void fetch() {
consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse(); //no exception thrown on this line at all -- but could this be the cause of the problem in the test?
System.out.println("consumerResponse's responseCode: " + consumerResponse.getResponseCode()); // NullPointerException thrown here
}
public ConsumerResponse setConsumerResponse(ConsumerResponse consumerResponse) {
this.consumerResponse = consumerResponse;
}
public ConsumerResponse getConsumerResponse() {
return consumerResponse;
}
}
以下是该类的相关JUnit测试:
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {
@Mock
private ConsumerResponse consumerResponse;
@InjectMocks
private MessageConsumer messageConsumer;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
//Failing unit test
@Test
public void getResponseCodeShouldReturn200() {
Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
messageConsumer.fetch()
}
}
如您所见,当consumerResponse.getResponseCode() 方法被调用时,我已经模拟了ConsumerResponse consumerResponse 变量以返回"200"。相反,我收到了NullPointerException。
我很确定我正确地模拟了成员变量并对其进行了适当的初始化 (initMocks)。我花了几天时间试图弄清楚这一点。我哪里错了?
【问题讨论】:
-
你能分享一下 ConsumerResponse 课程吗?
-
@GauravRai1512 它在一个外部库中,很遗憾我无法访问
-
@JB Nizet 但这没关系,因为我要模拟的方法属于 consumerResponse 对象,对吧? ——这不是 Mockito 的重点吗? (隔离依赖项并让它们做你想做的事?)
-
您在代码中使用了 notificationConsumer,但它没有被模拟。所以它是空的。 SpringBootTest 注释也是无用的,因为您没有使用 SpringRunner 运行测试。所以它没有任何作用。
-
准确地说:您希望将被测类 (MessageConsumer) 与其依赖项 (NotificationConsumer) 隔离开来。所以你需要模拟 NotificationConsumer。
标签: java spring-boot junit mockito