在rest调用中,使用mockito模拟自动连接的字段会给出null响应

在rest调用中,使用mockito模拟自动连接的字段会给出null响应,rest,junit,mockito,Rest,Junit,Mockito,我使用的是spring boot和mockito。我自动连接了一个类,即BDSRequest,在Junit测试类中,我使用了@Spy和@InjectMocks注释。但在Junits中调用rest服务时,我得到的响应(bdsCustomerHoldings)为null,断言失败。如何在不使用mockito.when(restemplate.postForObject(Constants.BDS\u rest\u URL,bdsRequest, BDS(客户持股。类别) Junit: @RunWit

我使用的是spring boot和mockito。我自动连接了一个类,即BDSRequest,在Junit测试类中,我使用了@Spy和@InjectMocks注释。但在Junits中调用rest服务时,我得到的响应(bdsCustomerHoldings)为null,断言失败。如何在不使用mockito.when(restemplate.postForObject(Constants.BDS\u rest\u URL,bdsRequest, BDS(客户持股。类别)

Junit:

@RunWith(MockitoJUnitRunner.class)
class BDSRestCallTest
{
    @InjectMocks
    private BDSRestCall bdsRestCall;

    @Mock
    private RestTemplate restTemplate;

    @Spy
    private BDSRequest bdsRequest;



    @Test
        public void getBDSCustomerInfoExceptionTest() {
            BDSCustomerHoldings bdsCustomerHoldings = bdsRestCall.getBDSCustomerInfo("SG", "S9718016D",
                    "00", "SG");
            System.out.println("response is " + bdsCustomerHoldings);
            assertNotNull("response is not null", bdsCustomerHoldings);
        }

}
当我们使用@RunWith(MockitoJUnitRunner.class)时,我们应该像下面那样模拟restTemplate的响应

Mockito.when(restTemplate.postForObject(Mockito.anyString(), bdsRequest, BDSCustomerInsuranceHoldings.class)).thenReturn(sampleBDSCustomerInsuranceHoldings());

然后它将给出模拟响应。

您需要模拟restTemplate.postForObject()calli希望在不模拟restTemplate.postForObject()的情况下进行测试然后注入一个真实的RestTemplate,而不是注入一个模拟的RestTemplate。模拟只会执行您告诉它要执行的操作。我建议您模拟RestTemplate调用,因为实际的API调用可能会在不同的条件下产生不同的响应。例如,如果您调用的服务关闭,即使您的测试用例是正确的。
Mockito.when(restTemplate.postForObject(Mockito.anyString(), bdsRequest, BDSCustomerInsuranceHoldings.class)).thenReturn(sampleBDSCustomerInsuranceHoldings());