Search code examples
spring-bootmockitoaop

Is there a newer approach to Spring AOP and mockito?


I have managed to solve a problem with Spring-boot aop and mocking test services using an approach detailed in Spring AOP Aspect not working using Mockito. This thread is over 6 years old.

Are there any newer approaches out there?

EDIT adding more detail from my specific implementation.

Controller:

@RestController
public class EndpointController {
    
    private EndpointService endpointService;
    
    @Autowired    
    public EndpointController(EndpointService endpointService) {
        this.endpointService = endpointService;
    }

    @PostMapping(path = "/endpoint", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    private @ResponseBody EndpointResponse doSomething(/* ... */, @RequestBody SomeObject someObject) throws Exception {
        return endpointService.doSomething(someObject);
    }
}

In my test class, I have:

@RunWith(SpringRunner.class)
public class EndpointControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldBeSuccessfulAccessingTheEndpoint() throws Exception {
        SomeObject someObject = new SomeObject(/* values */);

        ObjectMapper mapper = new ObjectMapper();
        String payload = mapper.writeValueAsString(someObject);

        mockMvc.perform(post("/endpoint").contentType(MediaType.APPLICTION_JSON).content(payload)).andExpect(status().isOK));
    }
}

It fails and throws a NullPointerException. When debugging, the endpointService is always null.

Any ideas?


Solution

  • You can use the annotation @MockBean now. It's some sort of wrapped mockito in spring testing.

    @RunWith(SpringRunner.class)
    public class ExampleTests {
    
         @MockBean
         private ExampleService service;
    
         @Autowired
         private UserOfService userOfService;
    
         @Test
         public void testUserOfService() {
             given(this.service.greet()).willReturn("Hello");
             String actual = this.userOfService.makeUse();
             assertEquals("Was: Hello", actual);
         }
    
         @Configuration
         @Import(UserOfService.class) // A @Component injected with ExampleService
         static class Config {
         }
     }
    

    https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html