方法设置错误 运行 JUnitWeb 测试
Error running JUnitWeb Test on Method setup
我有一个 Spring 申请,
我创建了这个测试:
@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
所以我解释一下异常的输出:
- 将修饰符 public 添加到您的方法设置中,否则 JUnit 无法调用它
- 去掉方法的参数,@Before,@After等不允许参数。
如何正确设置 MockMvc 是另一个问题。最近的 Spring 和关于网络范围初始化和行为的附加注释离开了这个答案的范围。 (这也需要更多的澄清,例如哪个 JDK,哪个 Spring 或 Spring Boot… XML 配置,dbunit 和 JUnit 4 建议遗留上下文。)
举个例子:
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);
}
}
我有一个 Spring 申请, 我创建了这个测试:
@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
所以我解释一下异常的输出:
- 将修饰符 public 添加到您的方法设置中,否则 JUnit 无法调用它
- 去掉方法的参数,@Before,@After等不允许参数。
如何正确设置 MockMvc 是另一个问题。最近的 Spring 和关于网络范围初始化和行为的附加注释离开了这个答案的范围。 (这也需要更多的澄清,例如哪个 JDK,哪个 Spring 或 Spring Boot… XML 配置,dbunit 和 JUnit 4 建议遗留上下文。)
举个例子:
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);
}
}