java – Spring Boot测试中的MockBean批注导致NoUniqueBeanDefinitionException

前端之家收集整理的这篇文章主要介绍了java – Spring Boot测试中的MockBean批注导致NoUniqueBeanDefinitionException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用@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

For convenience,tests that need to make REST calls to the started
server can additionally @Autowire a TestRestTemplate which will
resolve relative links to the running server.

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

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

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

原文链接:https://www.f2er.com/java/121415.html

猜你在找的Java相关文章