javaspringunit-testingconfiguration

Unit test context configuration spring


I am doing unit tests for a rest controller, which is only a small part of a bigger application.
Ideally I would like to use a mocking framework to ensure that the test are unitary. I would mock the manager and the dao.
However that would require to have different configurations for the rest controller class that make him use a different manager depending if we are in test context or in application context.
The mocks are defined in context-test.xml.

This is what I have done so far:
Test RestController

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(locations = "classpath:/META-INF/spring/context-test.xml")
@WebIntegrationTest
public class MyRestControllerTest extends AbstractTransactionnalTest {

  @Autowired
  private IManager manager;

  @Test
  // my unit tests
}

RestController

@RestController
@SpringApplicationConfiguration(locations = {"classpath:/META-INF/spring/context-test.xml",
                                             "classpath:/META-INF/spring/context-application.xml"})
@RequestMapping("/me")
class MyRestController {

  @Autowired
  private IManager manager;

  // Content of my controller
  }

The main issue with my solution so far:

Is there a better solution to do this?


Solution

  • I agree with @chrylis. The problem here I think may be your class design.

    If your MyRestController class is dependent on knowing which context is passed in, seems like this would be a Spring/DI anti-pattern. The whole point of DI is that the class "passively" handles the context with correct behavior in the first place.

    Any injected objects should simply be created/handled correctly by the injecting context.