I’m currently working on a Spring Boot application and I’m trying to write a test for my service layer using @MockBean to avoid interacting with the database. Here’s the test code:
@SpringBootTest(classes = TestApplication.class)
@AutoConfigureMockMvc
class CartServiceImplTest {
@MockBean
private CartMapper cartMapper;
@Autowired
private CartServiceImpl cartService;
@Test
void testCountCarts() {
Cart cart = new Cart();
int count = 1;
when(cartMapper.countCarts(Mockito.any())).thenReturn(count);
assertEquals(count, cartService.countCarts(cart));
//verify(cartMapper).countCarts(cart);
}
}
However, the test fails with the following error:
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 3.777 s <<< FAILURE! - in CartServiceImplTest
testCountCarts Time elapsed: 0.809 s <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: <1> but was: <5>
at CartServiceImplTest.testCountCarts(CartServiceImplTest.java:46)
It seems like the @MockBean annotation is not working as expected, and the test is still connecting to my database.
Here’s the configuration for my test context:
@ComponentScan(basePackages = {"world.xuewei"}, excludeFilters = {@ComponentScan.Filter(classes = {SpringBootApplication.class})
})
@SpringBootConfiguration
@EnableAutoConfiguration
@MapperScan(basePackages = {"world.xuewei.mapper"})
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
In an attempt to solve the problem, I tried removing the @MapperScan(basePackages = {“world.xuewei.mapper”}) annotation. However, this resulted in a different error:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addressController': Unsatisfied dependency expressed through field 'addressService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addressService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'world.xuewei.mapper.AddressMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup="", name="", description="", authenticationType=CONTAINER, type=java.lang.Object.class, mappedName="")}
I’m at a loss as to how to proceed. Any suggestions on how to resolve this issue would be greatly appreciated. Thanks in advance!
Cillian is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.