The mockbean annotation in the Java – spring boot test results in a nonuniquebeandefinitionexception
I have a problem using @ mockbean annotation The document says that mockbean can replace beans in the context, but I get nonuniquebeandefinitionexception in the unit test I can't see how to use annotations If I can simulate repo, there will obviously be multiple bean definitions
Let me take the example here: https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4
I have a Mongo Repository:
public interface MyMongoRepository extends MongoRepository<MyDTO,String> { MyDTO findById(String id); }
Jersey resources:
@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(); } }
There is also a JUnit test:
@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); } }
Error message:
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
Solution
This is an error: https://github.com/spring-projects/spring-boot/issues/6541
The fix is in spring Data 1.0 2-snapshot and 2.0 3-SNAPSHOT: https://github.com/arangodb/spring-data/issues/14#issuecomment -3741173
If you do not use these versions, you can resolve it by declaring the impersonation Name:
@MockBean(name="myMongoRepository") private MyMongoRepository repository;
Respond to your comments
From spring's doc:
After reading this article, I think you need to declare @ springboottest using the web environment:
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
If your spring boot does not start the web environment, what are the requirements of testresttemplate So I guess spring doesn't even offer it