I have multiple Spring Boot tests where I need to override a bean that is loaded in the test context using the @SpringBootTest annotation. In one of my test classes, I successfully used the @MockBean annotation to override a bean called AwsFireLogger defined in the thConfiguration.class. However, when I added the @MockBean annotation in another test class that also uses the same configuration class, I encountered an error stating "Duplicate mock definition". How can I resolve this issue and successfully override the bean in both test classes?
Here is an example of the code structure:
@SpringBootTest(classes = { thConfiguration.class, CaffeineCacheConfiguration.class })
public class FirstTestClass {
@MockBean
private AwsFireLogger awsFireLogger;
// Rest of the test code...
}
@SpringBootTest(classes = { thConfiguration.class, CaffeineCacheConfiguration.class })
public class SecondTestClass {
@MockBean
private AwsFireLogger awsFireLogger;
// Rest of the test code...
}
When I run the tests, the first test class runs successfully, but the second test class throws an exception with the message "Duplicate mock definition". How can I resolve this issue and ensure that both test classes can override the AwsFireLogger bean?
I tried also doing something like:
public class BaseIntegrationTest {
@MockBean
AwsFireLogger awsFireLogger ;
}
And then extend from my test classes but at some point the bean wasn't injected in the context and I got errors related with that.
Thanks in advance!
Specify unique names for each @MockBean
:
@SpringBootTest(classes = { thConfiguration.class, CaffeineCacheConfiguration.class })
public class FirstTestClass {
@MockBean(name = "firstAwsFireLogger")
private AwsFireLogger awsFireLogger;
// Rest of the test code...
}
@SpringBootTest(classes = { thConfiguration.class, CaffeineCacheConfiguration.class })
public class SecondTestClass {
@MockBean(name = "secondAwsFireLogger")
private AwsFireLogger awsFireLogger;
// Rest of the test code...
}