Spring Boot测试中的MockBean注释导致NoUniqueBeanDefinitionException

我在使用@MockBean注释时遇到问题。 文档说MockBean可以替换上下文中的bean,但是我在unit testing中得到NoUniqueBeanDefinitionException。 我看不出如何使用注释。 如果我可以模拟repo,那么显然会有多个bean定义。

我正在按照此处的示例进行操作: https : //spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4

我有一个mongo存储库:

public interface MyMongoRepository extends MongoRepository { 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-SNAPSHOT2.0.3-SNAPSHOT : https : //github.com/arangodb/spring-data/issues/14#issuecomment-374141173

如果您不使用这些版本,可以通过声明模拟名称来解决它:

 @MockBean(name="myMongoRepository") private MyMongoRepository repository; 

回应你的评论

来自Spring的文档 :

为方便起见,需要对启动的服务器进行REST调用的测试还可以@Autowire一个TestRestTemplate,它将解析与正在运行的服务器的相关链接。

阅读本文,我认为您需要使用Web环境声明@SpringBootTest

 @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) 

如果您的spring boot无法启动Web环境,那么TestRestTemplate需要什么。 因此,我猜spring甚至没有提供它。