我正在开发一个支持Spring的嵌入式Tomcat应用程序,它使用基于注释的配置。该应用程序将Spring MVC控制器用于其REST端点。为了分离关注点,并避免在单独的上下文中有重复的bean,父上下文包含所有不是REST端点的bean,而Spring Web MVC上下文包含所有作为REST端点的bean。
我想为这些端点编写新的和重构旧的集成测试,这些端点代表应用程序的结构。现有的测试类如下所示:
import com.stuff.web.MyEndpoint;
@Configuration
@ComponentScan(basePackages = {"com.stuff"})
public class SpringConfig { ... }
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
public class TestMyEndpoint {
@Autowired
private MyEndpoint myEndpoint;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders
.standaloneSetup(myEndpoint)
.build();
}
@Test
public void testMyEndpoint() throws Exception {
mockMvc.perform(get("/myendpoint")
.accept(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk())
.andReturn();
}
}问题是,我用于此测试的上下文现在加载了每个bean,而我希望确保在测试执行期间没有加载调用RestController bean的非REST bean。
添加像这样的东西
@Configuration
@ComponentScan(basePackages = {"com.stuff"},
excludeFilters = {
@Filter(type = FilterType.REGEX, pattern = "com.stuff.web.*")})
public class SpringConfig { ... }将确保实现我想要的那种分离,但是这样我就无法访问我正在尝试测试的com.stuff.web.MyEndpoint类。
我错过了什么容易的东西吗?如果我把情况解释清楚了,请告诉我。
发布于 2017-12-29 11:28:21
你所描述的那种分离(mvc和非mvc)在10年前是有意义的,现在不再有意义了。通过功能/设计模式(web/服务/存储库等)分离代码,并拥有特定于该层的@Configuration类。Spring stereotype annotations足够好地提示您的应用程序应该如何分解。然后,将您的测试放在与目标代码相同的包中,并模拟/覆盖任何依赖项。
看起来你并没有使用Spring Boot (你真的应该),但他们在文档中有一个很棒的章节来测试你的应用程序的“切片”。https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-tests
https://stackoverflow.com/questions/48014642
复制相似问题