I have a spring controller with multiple spring bean dependencies (autowired services). Each service has also few spring bean dependencies (autowired daos).
For instance, controller login method:
@Controller
@RequestMapping("/")
public class ClientAccessController extends BaseController {
@Autowired
IFileService fileService;
@Autowired
MidTierService midTierService;
/**
* Used to handle client login requests
* Works as a proxy to MID tier server
*
* @param request LoginRequest(userLogin, userPassword, compId, installGuid)
* @return LoginResponse (token)
* @throws Exception
*/
@RequestMapping(method = RequestMethod.POST, value = "/login", headers = "Content- type=application/json")
public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest request) throws Exception {
log.info("LOGIN REQUEST [ " + request.toString() + " ]");
String token = midTierService.authenticateNativeClient(request.getLogin(), request.getPassword(), request.getGuId(),
request.getCompid().toString());
LoginResponse response = new LoginResponse(token);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<LoginResponse> responseEntity = new ResponseEntity<>(response, HttpStatus.OK);
log.info("LOGIN RESPONSE [ " + response.toString());
return responseEntity;
}
I am trying to write JUnit tests for only controller ClienAccessController. But when I autowire ClientAccessController in test class, spring tries to create beans for all controller dependencies and all nested ones (daos etc) but I really don’t need em, only MidTierService.
So what should I do to exclude nested beans initializations and to use only what I need in test classes?
Spring allows more than one way to
@Autowiredmembers. The perferred approach for me (from a testability standpoint) is to@Autowiredthe constructor. So I would create a constructor forClientAccessControllerthat looks like this:If your autowiring is a bit more complex (in that it uses
@Qualifieror@Value) more can be done with parameter annotations.That way, you can easily set up this class with mock objects or stubs for testing.