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

Cod*_*der 7 java-8

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

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

@Service
public class ThirdPartyService{

.......................

    public String decrypt(String encryptedText) { 
    //third party SDK I am using
        return Service.decrypt.apply(encryptedText);
    }
.........
..............
}


    @ComponentScan("com")
    @PropertySource({"classpath:/api.properties", "classpath:/common.properties"})
    @SpringBootConfiguration
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
    @Transactional
    public class TestControllerTest extends IntegrationTest {
    @MockBean
    ThirdPartyService thirdPartyService;
    @Before
    public void initMocks(){
    MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
    when(ts.decrypt("encryptedText")).thenReturn("decryptedText")    
    Request req = Request.builder().name("name123").build();
    //written performPost method in some other class
    ResultActions action = performPost("/test", req);
    action.andExpect(status().isOk());  
    }
    }

    public class IntegrationTest {
    protected final Gson mapper = new Gson();
    private MockMvc mvc;
    @Autowired
    private WebApplicationContext context;
    public ObjectMapper objectMapper = new ObjectMapper();
    @Before
    public void setup() {
    this.mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
    }}
Run Code Online (Sandbox Code Playgroud)

当我调用第三方服务解密方法时,它应该将解密文本作为字符串返回给我。但是得到重复的模拟定义错误

小智 8

我遇到过同样的问题。造成这种情况的原因是测试配置文件被放置在其他地方,它包含模拟的 bean。

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