Reputation: 323
I want to test a single controller which has dependency on 1 service and 1 repo using @WebMvcTest annotation. There are other 5 services/repo in the whole app which i wouldn't want to mock in this unit test.
I have mocked the required 2 services/repo. Here i am testing a simple endpoint which doesn't even access the repo but when i try to unit test this controller for that specific controller in spring boot like this
@RunWith(SpringRunner.class)
@WebMvcTest(WebController.class)
public class LoginTest {
@MockBean
private CustomerRepository customerRepository;
@MockBean
private CustomerService customerService;
private MockMvc mockMvc;
@Test
public void serverRunning() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(content().string("Server is running"))
.andDo(print());
}
}
I get
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'restaurantRequestRepository': Cannot create inner bean '(inner bean)#60b4d934' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#60b4d934': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
Note: If i use @SpringBootTest, it works but i don't want to instantiate the whole application for a simple test.
Upvotes: 2
Views: 1194
Reputation: 3266
I ran into exactly the same problem. This was caused by having the @EnableJpaRepositories
annotation on my main Spring app class. The webmvc test disables full auto-configuration, but must still load the base application class.
Easy fix, fortunately, simply create a new configuration class and move your @EnableXRepository
annotations to that class instead, and they won't be included in your webmvc test!
@Configuration
@EnableJpaRepositories
class PersistenceConfiguration {}
Upvotes: 5