3

I am trying to create Test class for Controller as below: Please note that we have created library for all repositories&domains (Using Spring DATA JPA) and added the dependency in actual application where UserController resides.

@RunWith(SpringRunner.class)
@WebMvcTest(value = UserController.class, secure = false)
public class UserControllerTest {
    @MockBean
    private UserService userService;

    @Autowired
    private MockMvc mvc;

    @Test
    public void testGetUsers() throws Exception {
        when(userService.getAllUser()).thenReturn(new ArrayList<Organization>());
        mvc.perform(get("/users")).andExpect(status().isOk());
    }
}

When I tried to run this class, I got exception:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#4d41ba0f': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available

How to test spring Boot rest controllers with MockMvc by skipping repository classes ?

Krish
  • 1,804
  • 7
  • 37
  • 65
  • I understood incorrectly your question. I will delete my question. You are having some sort of problem on the entity manager configuration. Do you have the `spring-boot-starter-data-jpa` on your pom.xml? – Dherik Jun 13 '18 at 16:24
  • Yes. the problem is when I ran specific test class its scanning all the components mentioned in the @SpringBootApplication. How to overcome that one ? – Krish Jun 13 '18 at 16:34
  • Did you try some `@MockBean` for entityManagerFactory???. Or run test with `debug=true` property, find and disable unnecessary auto-configuration beans - for example `JpaRepositoriesAutoConfiguration` – borino Jun 14 '18 at 06:00

1 Answers1

0

Your problem is, that you didn't provide other beans, which are @Autowired in your UserController class. In @WebMvcTest beans don't undergo standard spring process of creation.

To quickly fix this, just provide other beans to tour test class annotated with @MockBean

Example controller class:

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    EntityManagerFactory entityManagerFactory;

    @Autowired
    AnotherSillyBean anotherSillyBean;

    ...
}

Example test class:

@RunWith(SpringRunner.class)
@WebMvcTest(value = UserController.class, secure = false)
public class UserController {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @MockBean
    EntityManagerFactory entityManagerFactory;

    @MockBean
    AnotherSillyBean anotherSillyBean;

    ...
}
Matej Čief
  • 181
  • 3
  • 5