spring – 如何使用自定义WebApplicationInitializer运行测试?
作者:互联网
class MyWebAppInitializer extends WebApplicationInitializer {
def onStartup(servletContext: ServletContext): Unit = {
...
}
}
@RunWith(classOf[SpringJUnit4ClassRunner])
@WebAppConfiguration
@ContextConfiguration(classes = Array(classOf[MyConfig]),
initializers=Array(classOf[MyWebAppInitializer])) // <<< ERROR
class MyTest {
...
}
抱怨:
annotation argument needs to be a constant; found: classOf[MyWebAppInitializer]
更新:@M. Deinum指出这里只允许ApplicationContextInitializers – 所以错误是一个报告错误的类型错误匹配.
那么……我怎样才能按顺序使用自己的MyWebAppInitializer并测试其中定义的功能?
解决方法:
在您的上下文配置中,我没有看到您列出了上下文加载器. AnnotationConfigWebContextLoader将在您的类路径上找到WebApplicationInitializer的实例,通过添加它并删除初始化器(正如您所指出的那样,对于ApplicationContextInitializers而不是WebApplicationInitializers),那么您应该全部设置.
@RunWith(classOf[SpringJUnit4ClassRunner])
@WebAppConfiguration
@ContextConfiguration(classes = {ConfigClass.class, AnotherConfigClass.class}, loader=AnnotationConfigWebContextLoader.class))
class MyTest {
...
这是一个有效的例子
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={WebConfiguration.class, SecurityConfig.class}, loader=AnnotationConfigWebContextLoader.class)
@ActiveProfiles("dev")
public class AppTests {
private MockMvc mockMvc;
@Autowired
protected WebApplicationContext webApplicationContext;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void simple() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("index"));
}
}
标签:scala,spring,spring-mvc,spring-test 来源: https://codeday.me/bug/20191006/1857999.html