0

Similar to How can I combine @DataJpaTest @SpringBootTest in one MVC application for testing every layer? but I am using a legacy app that is using Spring. As such not Spring Boot.

Here's the test I have so far which works until I remove the commented out lines

@ContextConfiguration(
//    loader = AnnotationConfigWebContextLoader.class
    classes = WebAppTest.Config.class
)
@RunWith(SpringRunner.class)
@DataJpaTest
@EnableJpaRepositories(
    basePackageClasses = { ... }
)
@EntityScan(
    basePackageClasses = { ... }
)
public class WebAppTest {
//    @Autowired
//    private WebApplicationContext webApplicationContext;

    @Autowired
    private EntityManager entityManager;

    @Autowired
    private Tracer tracer;

    @Test
    public void test() {

//        System.out.println(webApplicationContext);
        assertThat(tracer).isNotNull();
        assertThat(entityManager).isNotNull();
    }

    @Configuration
    static class Config {
        @Bean
        Tracer tracer() {

            return mock(Tracer.class);
        }
    }
}

When I uncomment the @WebAppConfiguration and the @Autowire I get the following

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.web.context.WebApplicationContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

When I uncomment the loader and still have @WebAppConfiguration I get the following

Cannot load WebApplicationContext from non-web merged context configuration [MergedContextConfiguration@68f4865 testClass = WebAppTest, locations = '{}', classes = ... contextLoader = 'org.springframework.test.context.web.AnnotationConfigWebContextLoader', parent = [null]]. Consider annotating your test class with @WebAppConfiguration.

Primarily the reason is I want to test @EntityListeners but SpringBeanAutowiringSupport does not inject beans in jUnit tests and the solution does not work for me as the @EntityListener needs to have a zero-arg constructor. There is a solution for this but it requires Spring Boot.

Archimedes Trajano
  • 28,830
  • 14
  • 134
  • 195

0 Answers0