我試圖使用JUnit,的Mockito和PowerMock創建單元測試我試圖使用JUnit,的Mockito和PowerMock創建單元測試
我的問題是,我在嘗試的一個類模擬返回一個空對象
這是我的代碼
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClientBuilder.class)
public class SolrPopulateApplicationTest {
@Mock
ClientConfig clientConfig;
@Mock
Client client;
@Mock
Response response;
@Mock
JerseyClient jerseyClient;
@Mock (answer = Answers.RETURNS_DEEP_STUBS)
JerseyWebTarget jerseyWebTarget;
@InjectMocks
@Autowired
SolrPopulateApplication solrPopulateApplication;
@Test
public void indexTest(){
PowerMockito.mockStatic(ClientBuilder.class);
ClientBuilder cli = Mockito.mock(ClientBuilder.class);
when(ClientBuilder.newClient(Matchers.any())).thenReturn(client);
when(jerseyClient.target(Matchers.anyString())).thenReturn(jerseyWebTarget);
when(jerseyWebTarget.path(Matchers.anyString())
.queryParam(Matchers.anyString(),Matchers.anyString())
.request(Matchers.anyString())
.header(Matchers.anyString(),Matchers.anyString())
.post(Matchers.any())).thenReturn(response);
boolean var = solrPopulateApplication.index("test","test");
}
}
當調試斷點被放置在所有的嘲笑應該已經設置我得到以下
client = {[email protected]} "client"
response = {[email protected]} "response"
jerseyWebTarget = {[email protected]} "null"
solrPopulateApplication = {[email protected]}
jerseyClient = {[email protected]} "jerseyClient"
cli = {[email protected]} "Mock for ClientBuilder, hashCode: 2080643905"
this = {[email protected]}
正如你所看到的jerseyWebClient是一個NULL,這導致nullpointerexception當我嘗試運行測試。
我試圖從@mock語句中刪除(answer = Answers.RETURNS_DEEP_STUBS),這沒有什麼區別。
被測試的方法實際上調用了實現JerseyWebTarget類的接口。我已經確定我試圖通過在JerseyWebTarget類中放置一個調試器來確保它停止在通過接口調用的方法上來模擬正確的類。
誰能告訴我爲什麼會發生這種情況,以及如何解決這個問題。
您還應該包含您的導入語句,以便您的示例已完成。我對PowerMock並不熟悉,並且據我所知,PowerMock和Mockito都可以包含模擬註釋。 – tonicsoft