How do I set up unit tests for RepositoryRestContr

2019-08-26 02:06发布

问题:

I have the following configuration for my unit test for a RepositoryRestController (the MyController class):

@RunWith(SpringRunner.class)
@WebMvcTest
public class MyTest {

    @Configuration
    @EnableSpringDataWebSupport
    static class TestConfiguration {

        @Bean
        MyController myController() {
            //controller construction
        }
    }

}

I can't find any documents online expounding on what sort of config I need to setup to get the tests running correctly. I only stumbled upon EnableSpringDataWebSupport when I was having trouble injecting Pageable instance on the controller method I'm testing. Now, my problem is that PersistentEntityResourceAssembler doesn't get autowired because the log says it has no default constructor. How does Spring setup this up?

As for the duplication with this question, notice that my configuration is not all that much different from the accepted answer and I'm still having problems. @WebMvcTest implies @AutoConfigureMockMvc. I've exhausted most of the information I could search about this problem before posting this question.

回答1:

If you have @PageableDefault in your controller, this is the general setting for controller test.

@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class)
@EnableSpringDataWebSupport  // for Pageable resolve
public class YourControllerTest {

}