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

Brad Mace picture Brad Mace · Dec 20, 2016 · Viewed 18.1k times · Source

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

@RunWith(SpringRunner.class)
@WebMvcTest(DemoController.class)
public class DemoControllerIntegrationTests {
    @Autowired
    private MockMvc mvc;

    @MockBean
    private DemoService demoService;

    @Test
    public void index_shouldBeSuccessful() throws Exception {
        mvc.perform(get("/home").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
    }
}

but I'm getting

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
Caused by: java.lang.IllegalArgumentException: At least one JPA metamodel must be present!

Unlike most people posting this error, I don't want to use JPA for this. Am I trying to use @WebMvcTest incorrectly? How can I track down the Spring magic that's inviting JPA to this party?

Answer

Nunyet de Can Calçada picture Nunyet de Can Calçada · May 6, 2017

Remove any @EnableJpaRepositories or @EntityScan from your SpringBootApplication class instead do this:

package com.tdk;

@SpringBootApplication
@Import({ApplicationConfig.class })
public class TdkApplication {

    public static void main(String[] args) {
        SpringApplication.run(TdkApplication.class, args);
    }
}

And put it in a separate config class:

package com.tdk.config;

@Configuration
@EnableJpaRepositories(basePackages = "com.tdk.repositories")
@EntityScan(basePackages = "com.tdk.domain")
@EnableTransactionManagement
public class ApplicationConfig {

}

And here the tests:

@RunWith(SpringRunner.class)
@WebAppConfiguration
@WebMvcTest
public class MockMvcTests {

}