【发布时间】:2017-01-18 18:55:21
【问题描述】:
我在使用 @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
【问题讨论】:
标签: java mongodb spring-boot spring-data mockito