@MockBeanアノテーションの使用に問題があります。ドキュメントでは、MockBeanがコンテキスト内のBeanを置き換えることができますが、私のユニットテストではNoUniqueBeanDefinitionExceptionが発生しています。注釈の使用方法はわかりません。私がレポを模擬することができれば、明らかに複数のBean定義が存在します。私は例を、以下のいSpringブートテストでMockBeanアノテーションが発生すると、NoUniqueBeanDefinitionExceptionが発生します。
はこちらをご覧ください:
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テスト:
https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4私はMongoのリポジトリを持っています
@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
ありがとうございました。私はそれを試みましたが、今度はSpringがTestRestTemplateをautowireできません:org.springframework.beans.factory.UnsatisfiedDependencyException: 'path.to.my.tests.TestMocks'という名前のBeanを作成中にエラーが発生しました:フィールド 'restTemplate'で表現されている不満足な依存性:依存関係[org.springframework.boot.test.web.client.TestRestTemplate]の型のbeanが見つかりました[org.springframework.boot.test.web.client.TestRestTemplate]:この依存関係のautowire候補となる少なくとも1つのbeanが必要です。 – JCN
がTestResttemplateの答えを更新しました – alexbt
ああ、私はウェブ環境のものを削除して忘れてしまった。私はそれを再追加しました、そして、今私のDTOクラスのための適切なHttpMessageConverterについてのエラーを取得しています。だから私は元のエラーを過ぎて、HttpMessageConvertersについて学んでいるように見えます。ありがとう! – JCN