Tôi gặp sự cố khi sử dụng chú thích @MockBean. Các tài liệu nói rằng MockBean có thể thay thế một bean trong ngữ cảnh, nhưng tôi nhận được một NoUniqueBeanDefinitionException trong thử nghiệm đơn vị của tôi. Tôi không thể xem cách sử dụng chú thích. Nếu tôi có thể thử repo, thì rõ ràng sẽ có nhiều hơn một định nghĩa bean.Chú thích MockBean trong thử nghiệm Khởi động Spring khiến NoUniqueBeanDefinitionException
tôi sau những ví dụ tìm thấy ở đây: https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4
Tôi có một kho lưu trữ Mongo:
public interface MyMongoRepository extends MongoRepository<MyDTO, String>
{
MyDTO findById(String id);
}
Và một nguồn tài nguyên Jersey:
@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();
}
}
Và một thử nghiệm 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);
}
}
nhắn
Lỗi:
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
Cảm ơn. Tôi đã thử và bây giờ Spring không thể autowire TestRestTemplate: org.springframework.beans.factory.UnsatisfiedDependencyException: Lỗi tạo bean với tên 'path.to.my.tests.TestMocks': Phụ thuộc không thỏa mãn được thể hiện qua trường 'restTemplate': Không đủ điều kiện bean của loại [org.springframework.boot.test.web.client.TestRestTemplate] được tìm thấy cho dependency [org.springframework.boot.test.web.client.TestRestTemplate]: dự kiến có ít nhất 1 bean đủ điều kiện làm ứng viên autowire cho sự phụ thuộc này . – JCN
cập nhật câu trả lời cho TestResttemplate – alexbt
Ah yeah, tôi đã loại bỏ điều webenvironment và quên. Tôi đã thêm lại nó, và bây giờ tôi nhận được một lỗi về không có HttpMessageConverter phù hợp cho lớp DTO của tôi. Vì vậy, có vẻ như tôi đã vượt qua lỗi gốc và để tìm hiểu về HttpMessageConverters. Cảm ơn! – JCN