skip to Main Content

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();

2

Answers


  1. 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());
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search