微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/java/121415.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐