java – Spring Boot测试中的MockBean批注导致NoUniqueBeanDefin
|
我在使用@MockBean注释时遇到问题.文档说MockBean可以替换上下文中的bean,但是我在单元测试中得到NoUniqueBeanDefinitionException.我看不出如何使用注释.如果我可以模拟repo,那么很明显会有多个bean定义.
我按照这里的例子来说:https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4 我有一个mongo存储库: public interface MyMongoRepository extends MongoRepository<MyDTO,String>
{
MyDTO findById(String id);
}
泽西岛资源: @Component
@Path("/createMatch")
public class Create
{
@Context
UriInfo uriInfo;
@Autowired
private MyMongoRepository repository;
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response createMatch(@Context HttpServletResponse response)
{
MyDTO match = new MyDTO();
match = repository.save(match);
URI matchUri = uriInfo.getBaseUriBuilder().path(String.format("/%s/details",match.getId())).build();
return Response.created(matchUri)
.entity(new MyResponseEntity(Response.Status.CREATED,match,"Match created: " + matchUri))
.build();
}
}
还有一个JUnit测试: @RunWith(SpringRunner.class)
@SpringBootTest
public class TestMocks {
@Autowired
private TestRestTemplate restTemplate;
@MockBean
private MyMongoRepository mockRepo;
@Before
public void setup()
{
MockitoAnnotations.initMocks(this);
given(this.mockRepo.findById("1234")).willReturn(
new MyDTO());
}
@Test
public void test()
{
this.restTemplate.getForEntity("/1234/details",MyResponseEntity.class);
}
}
错误信息: Field repository in path.to.my.resources.Create required a single bean,but 2 were found:
- myMongoRepository: defined in null
- path.to.my.MyMongoRepository#0: defined by method 'createMock' in null
解决方法
这是一个错误:
https://github.com/spring-projects/spring-boot/issues/6541
修复程序在spring-data 1.0.2-SNAPSHOT和2.0.3-SNAPSHOT:https://github.com/arangodb/spring-data/issues/14#issuecomment-374141173中 如果您不使用这些版本,可以通过声明模拟名称来解决它: @MockBean(name="myMongoRepository") private MyMongoRepository repository; 回应你的评论 从Spring’s doc:
阅读本文,我认为您需要使用Web环境声明@SpringBootTest: @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) 如果你的spring boot没有启动web环境,那么TestRestTemplate的需求是什么.因此,我猜春天甚至没有提供它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
