samedi 20 octobre 2018

How to mock arguments passed into Spring MVC Controller

How can I mock a service that is passed as an argument to a Spring MVC Controller?

Service that should be mocked. It is with scope "prototype" which is important in my scenario:

@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class LdapService {
    ...
}

Spring MVC Controller:

@RestController
public class SomeController {
    @GetMapping("/something")
    public ResponseEntity<Void> doSomething(LdapService ldapService) {
        ldapService.invokeSomeMethod();
        return ResponseEntity.ok().build();
    }
}

Test:

@RunWith(SpringRunner.class)
@WebMvcTest(PasswordController.class)
public class SomeControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void doSomeTest() throws Exception {
        // In the following call, a mocked LdapService shall be used!
        mockMvc.perform(get("/something"));

How can I mock the LdapService in this example?

Aucun commentaire:

Enregistrer un commentaire