我正在用Spring Boot测试我的第一个RestController。遵循Internet上的许多示例,我对测试进行了如下设置,但是Spring无法自动连接WebApplicationContext:
@RunWith(SpringRunner.class)
@WebMvcTest(CollectionController.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = DefaultTestConfiguration.class)
public class CollectionControllerTest {
private MockMvc mvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void postTest() throws Exception {
mvc.perform(post("/collection/")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
如果我尝试自动装配它而不是在@Before方法中显式设置它,MockMvc也会发生同样的情况。
我的配置类:
@Configuration
public class DefaultTestConfiguration {
@Bean
public ICollectionService collectionService() {
return new MockCollectionService();
}
}
控制器:
@RestController
@RequestMapping("/collection")
public class CollectionController {
private ICollectionService collectionService;
@Autowired
public CollectionController(ICollectionService collectionService) {
super();
this.collectionService = collectionService;
}
@RequestMapping(value = "/", method=RequestMethod.POST)
public CreateCollectionDTO createCollection(@RequestParam String collectionId) {
return new CreateCollectionDTO(collectionService.createCollection(collectionId));
}
}
和我在pom.xml中的spring依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
在此先感谢您提供的帮助。
答案 0 :(得分:0)
最后我自己找到了。 问题出在@ContextConfiguration语句,更确切地说是:loader参数的值AnnotationConfigContextLoader.class阻止了WebApplicationContext的实例化。
删除“ loader”参数后,一切都正常:我的配置类的@Bean方法可以正确执行,而MockMvc是通过自动装配来创建的(不需要@Before方法)。