我是模拟新手。我要调用的服务是名称A,我需要测试someMethod。
@Service
public class A {
private Logger logger = LoggerFactory.getLogger(getClass());
private final CoreXReader coreXReader;
@Autowired
B b;
@Autowired
C c;
@Async
public void someMethod(Config config) throws Exception {
pushConfig(config);
}
private void pushConfig(Config config) throws Exception {
String url = config.getBaseurl() + config.getId();
ABCRestClient restClient = new ABCRestClient(url);
String jobJson = restClient.callRestMethod(HttpMethod.GET, "");
}
}
ABCRestClient的样本
public class ABCRestClient {
private Logger logger = LoggerFactory.getLogger(getClass());
private String url;
public ABCRestClient(String url) {
this.url = url;
}
public String callRestMethod(HttpMethod method, String payload) throws Exception {
someresponse="example response";
return someresponse;
}
}
[我正在尝试通过创建mockSpy进行测试,但仍在调用它的'callRestMethod'
@RunWith(SpringRunner.class)
@SpringBootTest // (webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {
@Autowired
private A a;
private Logger logger = LoggerFactory.getLogger(getClass());
@Before
public void prepareMockDataForService() throws Exception {
ABCRestClient apiClient = new ABCRestClient(config.getBaseurl() + config.getId() );
ABCRestClient apiClientSpy=Mockito.spy(apiClient);
doReturn(getCallResponse()).when(apiClientSpy).callRestMethod(HttpMethod.GET, "");
}
@Test
public void TestPushConfig() throws Exception {
a.someMethod(StubDataGenerator.getConfig());
}
private String getCallResponse() {
return "{"msg":"sample response"}";
}
}
我不确定我在做什么错,为什么在我已经创建了间谍的情况下调用实际的callRestMethod。
我也尝试过使用此Mockito.doReturn(getCallResponse()).when(apiClientSpy.callRestMethod(HttpMethod.GET, ""))
此外,如果我使用Mockito.doReturn()
或直接使用doReturn()
,这两个语句有什么区别?就我而言,两者似乎表现相同。
[我也尝试使用when().thenReturn();
之前,但当您实际要拨打电话时,我读了一个使用when().thenReturn()
的地方。如果我的理解错误,请更正。
您可以尝试模拟而不是间谍:
@RunWith(SpringRunner.class)
@SpringBootTest // (webEnvironment=
SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {
@Autowired
private A a;
private Logger logger = LoggerFactory.getLogger(getClass());
@Before
public void prepareMockDataForService() throws Exception {
ABCRestClient apiClientSpy=Mockito.mock(ABCRestClient.class);
doReturn(getCallResponse()).when(apiClientSpy).callRestMethod(HttpMethod.GET, "");
}
@Test
public void TestPushConfig() throws Exception {
a.someMethod(StubDataGenerator.getConfig());
}
private String getCallResponse() {
return "{"msg":"sample response"}";
}
}