测试类:
@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private MyService myService;
@Test
public void testCreateEntit() throws Exception {
...
given(myService.createEntity(eq(entity)))
.willReturn(entity);
...
}
}
控制器类:
@RestController
@RequestMapping("/")
public class MyController {
private MyService myService;
public MyController(final MyService myService) {
this.myService = myService;
}
...
}
服务类:
public class DefaultMyService implements MyService {
private MyRepository repository;
public DefaultMyService(final MyRepository repository) {
this.repository = repository;
}
}
运行测试时出现以下错误:
Parameter 0 of constructor in com.company.api.repositories.MyRepositoryImpl required a bean of type 'org.springframework.data.mongodb.core.MongoTemplate' that could not be found.
我的问题是为什么@MockBean注释类会搜索实际的依赖项?
我在这里做错了,如何用MockMvc测试mvc?
修改
版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
<properties>
<!-- use UTF-8 for everything -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring.cloud.netflix.version>1.2.2.RELEASE</spring.cloud.netflix.version>
<spring.social.google.version>1.0.0.RELEASE</spring.social.google.version>
<spring.cloud.aws.version>1.1.3.RELEASE</spring.cloud.aws.version>
<jwt.version>0.6.0</jwt.version>
<apache.commons-lang3.version>3.4</apache.commons-lang3.version>
<apache.commons.jexl.version>3.0</apache.commons.jexl.version>
</properties>