英文:
Java How to test api gateway endpoints without deploying
问题
I want to learn how to unit test API gateway endpoints, or just in general, before deploying the API.
For example, how could I test something like:
public class someController {
private SomeService someService;
@GET
@Path("...")
public String someMethod(){
return someService.someMethod();
}
}
SomeService:
public class SomeService{
public String someMethod(){
//make http request to api gateway
return json string
}
}
How would I test "someService" class. I assume the "someController" class would just ensure "someMethod" is being called by making use of Mockito verify(someService).someMethod();
英文:
I want to learn how to unit test API gateway endpoints, or just in general, before deploying the API.
For example, how could I test something like:
public class someController {
private SomeService someService;
@GET
@Path("...")
public String someMethod(){
return someService.someMethod();
}
}
someSerivce:
public class SomeService{
public String someMethod(){
//make http request to api gateway
return json string
}
}
How would I test "someService" class. I assume the "someController" class would just ensure "someMethod" is being called by making use of Mockito verify(someService).someMethod();
答案1
得分: 1
创建一个SomeService
的模拟对象,将其注入到SomeController
中(通过构造函数或setter方法)。
使用when/thenReturns
设置模拟对象的行为。例如:
when(someServiceMock.someMethod()).thenReturn("foo bar")
调用SomeController.someMethod()
并检查结果。
如果你在使用Spring,则可以进一步使用WebMvcTest
和@Autowired MockMvc
来测试:
@WebMvcTest(controllers = SomeController.class)
然后可以调用实际的路径、HTTP方法、头部等:
mockMvc.perform(get("...").andExpect(status().isOk());
英文:
Create a mock of SomeService
, inject it into SomeController
(via constructor or setter).
Set up the mock behaviour with when/thenReturns. Eg:
when(someServiceMock.someMethod()).thenReturn("foo bar")
Call SomeController.someMethod()
and check the result.
If you are Spring then you can take this further by using WebMvcTest
with an @Autowired MockMvc
@WebMvcTest(controllers = SomeController.class)
To call the actual path and http method, headers, etc.
mockMvc.perform(get("...").andExpect(status().isOk());
答案2
得分: 1
以下是要翻译的内容:
假设我正确理解您的问题,您想要测试调用您的服务方法并查看响应,如果您使用的是IntelliJ,您可以尝试使用此插件 [1] 与您的应用程序一起调用服务类上的方法并查看结果。
[1] https://plugins.jetbrains.com/plugin/18529-unlogged
免责声明:我是该插件的贡献者。
英文:
Assuming I am reading your question correctly that you want to do a test call one of your service methods and see the response, and if you are using IntelliJ, you can potentially use this plugin [1] with your application to invoke the methods on your service class and see the result.
[1] https://plugins.jetbrains.com/plugin/18529-unlogged
Disclaimer: I am a contributor of that plugin.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论