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

JCN*_*JCN 9 java mockito mongodb spring-data spring-boot

我在使用@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);
}
Run Code Online (Sandbox Code Playgroud)

泽西岛资源:

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一个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);

    }

}
Run Code Online (Sandbox Code Playgroud)

错误信息:

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
Run Code Online (Sandbox Code Playgroud)

ale*_*xbt 13

这是一个错误:https://github.com/spring-projects/spring-boot/issues/6541

解决方法是在弹簧数据1.0.2-SNAPSHOT和2.0.3-SNAPSHOT:https://github.com/arangodb/spring-data/issues/14#issuecomment-374141173

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

@MockBean(name="myMongoRepository")
private MyMongoRepository repository;
Run Code Online (Sandbox Code Playgroud)

回应你的评论

来自Spring的文档:

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

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

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
Run Code Online (Sandbox Code Playgroud)

如果你的弹簧启动没有启动web环境,那么需要什么TestRestTemplate.因此,我猜春天甚至没有提供它.