Search code examples
javatestingmockitomicronaut

Mockito not mocking function from controller in test


I am trying to mock a method my controller calls as shown:

@Post(value = "/blah", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
    @Transactional
    public HttpResponse<Object> createBlah(HttpHeaders httpHeaders,
            @Body @Valid CreateBlahRequest createBlahRequest) {
        HttpResponse<Object> createBlahResponse;

        (...)
        createBlahService(...) // what i am trying to mock

        return HttpUtils.getResponse(HttpStatus.CREATED, createBlahResponse.body());
    }

And in my test I am testing as shown:

    @Mock
    public BlahController blahController;

    public HttpResponse<Object> resp = HttpResponse.created((Object) new AccountResponse()).status(HttpStatus.OK);

    @BeforeAll
    public void configureAppContext() {
        Application.APPLICATION_CONTEXT = applicationContext;
        MockitoAnnotations.initMocks(this);
    }

@Test
    void createBlah(){

        MutableHttpRequest<CreateBlahRequest> request = HttpRequest
                .POST("/blah", createBlahRequest)
                .header("requestId", "1");

        when(blahController.createBlah(eq(request.getHeaders()), eq(createBlahRequest))).thenReturn(resp);

        HttpResponse<CreateBlahRequest> blahRes = client.toBlocking().exchange(request, CreateBlahRequest.class);

    }

However, when the client makes the call to the controller, it doesn't seem to get matched by the (when) that is inside of my test, it continues to run as is. If anyone could please give some advice on this, it would be greatly appreciated.


Solution

  • To anyone who sees this, I had to inject the class that the method calls. In the controller it calls another service class so I mocked it like so:

    @Inject
    public BlahService BlahService;
    
    @MockBean(BlahService.class)
    public BlahService blahService(){
        return Mockito.mock(BlahService.class);
    }
    

    and it worked fine.