Getting “At least one JPA metamodel must be present” with @WebMvcTest

前端 未结 5 1293
逝去的感伤
逝去的感伤 2021-02-05 06:02

I\'m fairly new to Spring, trying to do some basic integration tests for a @Controller.

@RunWith(SpringRunner.class)
@WebMvcTest(DemoController.clas         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 06:11

    I had the same problem. @WebMvcTest looks for a class annotated with @SpringBootApplication (in the same directory or higher up in your app structure if it doesn't find one). You can read how this works @ https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests.

    If your class annotated with @SpringBootApplication also has @EntityScan /@EnableJpaRepositories this error occurs. Because you have these annotations with @SpringBootApplication and you are mocking the service ( so actually not using any JPA ). I found a workaround which may not be the prettiest, but works for me.

    Place this class in your test directory ( the root ). @WebMvcTest will find this class before your actual Application class. In this class you don't have to add @EnableJpaRepositories/@EntityScan.

    @SpringBootApplication(scanBasePackageClasses = {
        xxx.service.PackageMarker.class,
        xxx.web.PackageMarker.class
    })
    public class Application {
    }
    

    And your test will look the same.

    @RunWith(SpringRunner.class)
    @WebMvcTest
    @WithMockUser
    public class ControllerIT {
    
        @Autowired
        private MockMvc mockMvc;
    
        @MockBean
        private Service service;
    
        @Test
        public void testName() throws Exception {
            // when(service.xxx(any(xxx.class))).thenReturn(xxx); 
            // mockMvc.perform(post("/api/xxx")...
            // some assertions
        }
    }
    

    Hope this helps!

提交回复
热议问题