Home:ALL Converter>Unit test context configuration spring

Unit test context configuration spring

Ask Time:2016-10-25T18:02:51         Author:banetl

Json Formatter

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 :
- I dont know how to tell the RestController wich context to use. (I only want to use one context at a time)

Is there a better solution to do this ?

Author:banetl,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/40236995/unit-test-context-configuration-spring
aramcodez :

I agree with @chrylis. The problem here I think may be your class design. \n\nIf 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. \n\nAny injected objects should simply be created/handled correctly by the injecting context.",
2016-10-25T15:01:54
yy