[英]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. 模拟在context-test.xml中定义。
This is what I have done so far : 这是我到目前为止所做的:
Test RestController 测试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
@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. - 我不知道如何告诉RestController使用上下文。 (I only want to use one context at a time)
(我只想一次使用一个上下文)
Is there a better solution to do this ? 有没有更好的解决方案呢?
您可以尝试添加setManager()
方法,这样您就可以将控制器中的管理器设置为“模拟”管理器。
I agree with @chrylis. 我同意@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. 如果你的
MyRestController
类依赖于知道传入了哪个上下文,那么这似乎是一个Spring / DI反模式。 The whole point of DI is that the class "passively" handles the context with correct behavior in the first place. DI的重点在于,“被动地”类首先以正确的行为处理上下文。
Any injected objects should simply be created/handled correctly by the injecting context. 应该通过注入上下文正确地创建/处理任何注入的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.