@WebAppConfiguration not injected

吃可爱长大的小学妹 提交于 2019-12-03 10:28:58

In my case problem has been solved by replacing:

@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { ... })

with

@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class, classes = { ... })

Notice the Web in the loader class name. With the previous loader, the GenericApplicationContext has been injected despite @WebAppConfiguration annotation.

The below set-up uses only Java configuration classes and works fine for me.

@WebAppConfiguration
@ContextConfiguration(classes = TestApplicationContext.class)
public class MyClassTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setUp() {
        mockMvc = webAppContextSetup(wac).build();
    }
    ....       
}

@Configuration
public class TestApplicationContext {

    @Bean
    public MyBean myBeanId(){
        return Mockito.mock(MyBean.class);
    }
    ....
}

The mere presence of @WebAppConfiguration on a test class ensures that a WebApplicationContext will be loaded for the test using a default path to the root of the web application. Therefore you can autowire the WebApplicationContext and use it to set up the mockMvc.

Note that the @WebAppConfiguration must be used in conjunction with @ContextConfiguration within the test class.

Why don't you add this annotation and see if it works. Replace XXXX-text.xml with your bean mapping xml.

@ContextConfiguration(locations={"classpath:/XXXX-test.xml"})

One of the tests is available for local dev support with annotation headers, where I had the similar issue from the question.

The comments are previous version of this test.

@RunWith(SpringJUnit4ClassRunner.class)
/* @EnableJpaAuditing */ /* for jpa dates */ /* it should be defined only once, 
because 'jpaAuditingHandler' defined in null on application startup */
@EntityScan(basePackageClasses = { EnableJpaAuditing.class, Jsr310JpaConverters.class })
//@ProfileValueSourceConfiguration(Application.class)
//@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class)
//@PropertySource("classpath:application.properties")
@TestPropertySource(locations = "classpath:application.properties")
//@WebAppConfiguration
@SpringBootTest
public class JpaTests {/* */}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!