[英]Mockito is not mocking out a member variable method return value
我有以下包含成員變量的類,但是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 consumerResponse
變量,以在調用consumerResponse.getResponseCode()
方法時返回"200"
。 相反,我得到了NullPointerException
。
我敢肯定,我正確地嘲笑了成員變量並適當地對其進行了初始化( initMocks
)。 我花了幾天的時間試圖解決這個問題。 我要去哪里錯了?
由於NotificationConsumer
也是此類的外部依賴項,因此您還必須模擬該類,否則consumerResponse = notificationConsumer.fetchWithReturnConsumerResponse();
由於您沒有模擬NotificationConsumer
因此測試中的結果將為null
。 另外,我建議不要在此單元測試中使用@SpringBootTest
,因為此批注將引導整個Spring上下文。 以下代碼段應為您提供幫助:
@RunWith(MockitoJUnitRunner.class)
public class MessageConsumerTest {
@Mock
private ConsumerResponse consumerResponse;
@Mock
private NotificationConsumer notificationConsumer;
@InjectMocks
private MessageConsumer messageConsumer;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void getResponseCodeShouldReturn200() {
Mockito.when(notificationConsumer.fetchWithReturnConsumerResponse()).thenReturn(consumerResponse);
Mockito.when(consumerResponse.getResponseCode()).thenReturn("200");
messageConsumer.fetch();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.