使用ServletServerContainerFactoryBean时junit报错怎么办
时间: 2023-07-20 18:44:19 浏览: 181
如果在使用ServletServerContainerFactoryBean时出现JUnit报错,可能是因为需要在测试类中手动启动Servlet容器。可以按照以下步骤进行修复:
1. 在测试类中添加一个静态方法,用于启动Servlet容器,例如:
```java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class})
public class MyTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
public static void startServer() throws Exception {
ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
container.setPort(8080);
container.afterPropertiesSet();
}
// 测试代码...
}
```
2. 在测试方法或测试类上添加@BeforeClass注解,并在该方法中调用上述静态方法,例如:
```java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class})
public class MyTest {
// ...
@BeforeClass
public static void beforeClass() throws Exception {
startServer();
}
// 测试代码...
}
```
这样就可以在JUnit测试中启动Servlet容器,并且使用ServletServerContainerFactoryBean进行配置。如果还是无法解决问题,可以检查相关依赖是否正确引入,并且确认应用程序能否正常启动。
阅读全文
相关推荐


















