Java 8 Geting java.lang.IllegalStateException:在测试用例中使用@MockBean时重复模拟定义

Java 8 Geting java.lang.IllegalStateException:在测试用例中使用@MockBean时重复模拟定义,java-8,Java 8,我有一个要模拟的服务类,但在运行测试时,我得到的原因是:java.lang.IllegalStateException:Duplicate mock definition[MockDefinition@482ba4b1name='',typeToMock=com.service.ThirdPartyService,extraInterfaces=set[[empty]],answer=RETURNS\u DEFAULTS,serializable=false,reset=AFTER] 我曾尝试在

我有一个要模拟的服务类,但在运行测试时,我得到的原因是:
java.lang.IllegalStateException:Duplicate mock definition[MockDefinition@482ba4b1name='',typeToMock=com.service.ThirdPartyService,extraInterfaces=set[[empty]],answer=RETURNS\u DEFAULTS,serializable=false,reset=AFTER]

我曾尝试在类级别、字段级别使用@MockBean创建模拟服务,并使用@Qualifier来解决这个问题

@服务
公共类第三方服务{
.......................
公共字符串解密(字符串加密文本){
//我正在使用的第三方SDK
返回服务。解密。应用(encryptedText);
}
.........
..............
}
@组件扫描(“com”)
@PropertySource({“classpath:/api.properties”,“classpath:/common.properties”})
@SpringBoot配置
@RunWith(SpringRunner.class)
@SpringBootTest(类={Application.class},webEnvironment=SpringBootTest.webEnvironment.DEFINED\u端口)
@交易的
公共类TestControllerTest扩展了IntegrationTest{
@蚕豆
第三方服务第三方服务;
@以前
公共void initMocks(){
initMocks(this);
}
@试验
public void test()引发异常{
当(ts.decrypt(“encryptedText”)。然后返回(“decryptedText”)
Request req=Request.builder().name(“name123”).build();
//在其他类中编写performPost方法
结果操作=性能测试(“/test”,req);
action.andExpect(status().isOk());
}
}
公共类集成测试{
受保护的最终Gson映射器=新Gson();
私有MockMvc;
@自动连线
私有WebApplicationContext上下文;
public ObjectMapper ObjectMapper=new ObjectMapper();
@以前
公共作废设置(){
this.mvc=MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}}
当我调用第三方服务decrypt方法时,它应该以字符串形式返回decryptedText。但是得到重复的模拟定义错误

我也有同样的问题。 造成这种情况的原因是测试配置文件放在了其他地方,其中包含模拟bean


我通过使用
@Autowired
而不是
@MockBean
解决了这个问题,因为这将导致自动连接已经被模拟的bean。

在我的例子中,问题出现在另一个依赖项更新之后,原因是
@springbootest
注释引用了同一个类两次:

@SpringBootTest(类={MyApplication.class,ApiControllerIT.class})
类ApiControllerIT扩展了IntegrationTestConfigurer{
// ...
}
@SpringBootTest(类={MyApplication.class,TestRestTemplateConfiguration.class})
公共类集成测试配置器{
// ...
}

我通过从子类(
ApiControllerIT
)中删除
@springbootest
注释来修复它。

Hey@Coder您是否设法解决了此问题。我也有同样的问题。不知道怎么解决