java - 我如何模拟方法,从另一种方法调用一个方法?
问题描述
我是 Mocking 的新手。我有一个我想调用的服务,比如说名字 A,我需要测试一些方法。
@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因为我已经创建了一个 spy 。
我也试过用这个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"}";
}
}
推荐阅读
- python - 处理由 Python 中的 bin 表示的分类缺失值?
- c++ - 如何使用模板和 const 关键字处理指向类型?
- amazon-web-services - 不使用分区键查询 DynamoDB 表的全局二级索引
- python - django模型文件字段中的默认图像?
- javascript - 为什么使用 google oauath isSignedIn,listen()?
- python - 当子句卡住时,pyspark big
- python - 手动插入框架设置滚动条不起作用 tkinter
- javascript - 按内容查找 div
- reactjs - React - 找不到模块 - 好像目录不存在
- xamarin.forms - MonoAndroid90 的指定语言目标缺失。确保为“MonoAndroid”安装了正确的工具