问题描述
@RunWith(springrunner.class)
@SpringJUnitWebConfig(locations = {
"classpath:testDatabaseContext.xml","classpath:testServicesContext.xml","classpath:backoffice-servlet.xml"
})
public class UserControllerTests {
@Autowired
private mockmvc mockmvc;
@Before
void setup(WebApplicationContext wac) {
this.mockmvc = mockmvcBuilders.webAppContextSetup(wac).build();
}
..
}
但是当我开始测试时,我得到了这个错误:
rg.junit.runners.model.InvalidTestClassError: Invalid test class 'com.pastis.UserControllerTests':
1. Method setup() should be public
2. Method setup should have no parameters
解决方法
这里有个例子:
RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class CustomerControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup () {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
@Test
public void testUserController () throws Exception {
ResultMatcher ok = MockMvcResultMatchers.status()
.isOk();
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/customers");
this.mockMvc.perform(builder)
.andExpect(ok);
}
}
,
所以我解释了异常的输出:
- 将修饰符public添加到您的方法设置中,否则JUnit无法调用它
- 从方法@ Before,@ After中删除参数,此类方法不允许参数。
如何正确设置MockMvc是另一个问题。最近的Spring和有关Web作用域初始化和-behavior的其他注释离开了此答案的范围。 (这还需要更多说明,例如,哪个JDK,哪个Spring或Spring Boot…XML配置,dbunit和JUnit 4提出了旧式上下文。)