Spring Checking MVC and mocking many classes

We have many controllers in our system and many Spring datastores.

I would like to write tests for my controllers that run through my MVC context.

However, it seems that it is rather cumbersome and just not so, it is necessary to manually fool all the services and repositories in my system so that I can test the controllers

eg.

FooControllerTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy(value = {
    @ContextConfiguration(classes = { MockServices.class }),
    @ContextConfiguration({ "classpath:/META-INF/spring/mvc-servlet-context.xml" }),
})
public class FooControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mvc;

    @Autowired
    private FooRepository fooRepository;

    @Autowired
    private FooService fooService; 

    @Before
    public void setUp() throws Exception {
        mvc = webAppContextSetup(wac).build();
    }

    @Test
    public final void list() {
        when(fooRepository.findAll()).thenReturn(...);
        mvc.perform(get("/foo"))...
    }

    @Test
    public final void create() {
        Foo fixture = ...
        when(fooService.create(fixture)).thenReturn(...);
        mvc.perform(post("/foo"))...
    }

}

MockServices.java

@Configuration
public class MockServices {

    @Bean
    public FooRespository fooRepositiory() {
        return Mockito.mock(FooRespository.class);
    }

    @Bean
    public FooService fooService() {
        return Mockito.mock(FooService.class);
    }

    //even though we are "only" testing FooController, we still need to mock BarController dependencies, because BarController is loaded by the web app context.
    @Bean
    public BarService barService() {
        return Mockito.mock(FooService.class);
    }

    //many more "mocks"

}

I really do not want to use standaloneSetup()(I want to use the production configuration, for example, conversion services, error handlers, etc.)

Is this just the price I have to pay for controller controller tests so far on line?

It seems like there should be something like mock every class annotated with @Serviceormock every interface that extends JpaRepository

+4
1

MVC , . , EJB View.

, Controller , , " " . , , , , , .

, , , , Controller.

0

All Articles