我试图使用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