복붙노트

[SPRING] WebApplicationContext가 autowire하지 않습니다.

SPRING

WebApplicationContext가 autowire하지 않습니다.

이 테스트 클래스를 작성합니다.

@ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
public class CandidateControllerTest {

        @Mock(name = "candidateService")
        private CandidateService candidateService;

        @InjectMocks
        private CandidateMenuController candidateMenuController = new CandidateMenuController();


        @Autowired
        WebApplicationContext wac;

        MockMvc mockMvc;


        @Before
        public void before() {



            mockMvc = MockMvcBuilders.webApplicationContextSetup(wac).build();
         }
    }

그러나:

코드 실행 후 다음 추적을 봅니다.

java.lang.IllegalArgumentException: WebApplicationContext is required
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.test.web.server.setup.InitializedContextMockMvcBuilder.<init>(InitializedContextMockMvcBuilder.java:39)
    at org.springframework.test.web.server.setup.MockMvcBuilders.webApplicationContextSetup(MockMvcBuilders.java:73)
    at controllers.CandidateControllerTest.before(CandidateControllerTest.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

내 문제를 해결하기 위해 무엇을해야합니까?

최신 정보

나는 코드를 바꾼다 :

@ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
@WebAppConfiguration
public class CandidateControllerTest {

    @Mock(name = "candidateService")
    private CandidateService candidateService;

    @InjectMocks
    private CandidateMenuController candidateMenuController = new CandidateMenuController();

    @Autowired
    WebApplicationContext wac;

    MockMvc mockMvc;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);

        // this.mockMvc =
        // MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();

         mockMvc = MockMvcBuilders.webApplicationContextSetup(wac).build();

    }
...
}

자취:

java.lang.IllegalArgumentException: WebApplicationContext is required
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.test.web.server.setup.InitializedContextMockMvcBuilder.<init>(InitializedContextMockMvcBuilder.java:39)
    at org.springframework.test.web.server.setup.MockMvcBuilders.webApplicationContextSetup(MockMvcBuilders.java:73)
    at controllers.CandidateControllerTest.before(CandidateControllerTest.java:61)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

해결법

  1. ==============================

    1.@WebAppConfiguration을 테스트 클래스에 추가하지 않는 한 WebContlicationContext는 ApplicationContext 만 존재하지 않는다.

    @WebAppConfiguration을 테스트 클래스에 추가하지 않는 한 WebContlicationContext는 ApplicationContext 만 존재하지 않는다.

    @ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    public class CandidateControllerTest { ... }
    

    @RunWith 주석 대신에 스프링 편의 클래스 중 하나를 확장 할 수도 있습니다.

    @ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
    @WebAppConfiguration
    public class CandidateControllerTest extends AbstractJUnit4SpringContextTests { ... }
    

    모래밭

  2. ==============================

    2.TestNG와 Mockito를 사용하여 동일한 문제가 발생했습니다.

    TestNG와 Mockito를 사용하여 동일한 문제가 발생했습니다.

    Whac은 autowired가 아니며 @BeforeTest 메소드에서 사용할 수 있지만 @Test 메소드에 있습니다.

    나는 이걸 옮겼어.

    mockMvc = MockMvcBuilders.webApplicationContextSetup(wac).build();
    

    @Test 메서드와 presto에, 그것은 작동합니다!

    솔루션과 함께 찾은 링크는 다음과 같습니다. http://forum.spring.io/forum/spring-projects/web/737624-problem-with-autowiring-webapplicationcontext-with-annotationconfigcontextloader

  3. ==============================

    3.WebApplicationContext가 필요하고 NullPointerException은 TestNG 및 Spring Test Framework의 초보자로서 가장 혼란스러운 오류입니다. 이것들은`AbstractTestNGSpringContextTests1 등을 확장하는 것을 잊어 버리는 것과 같은 단순한 실수로 발생합니다. 이러한 오류를 피하기 위해 제가 사용하는 코드 템플릿을 줄 것입니다.

    WebApplicationContext가 필요하고 NullPointerException은 TestNG 및 Spring Test Framework의 초보자로서 가장 혼란스러운 오류입니다. 이것들은`AbstractTestNGSpringContextTests1 등을 확장하는 것을 잊어 버리는 것과 같은 단순한 실수로 발생합니다. 이러한 오류를 피하기 위해 제가 사용하는 코드 템플릿을 줄 것입니다.

    @Test
    @WebAppConfiguration
    @ContextConfiguration(classes = WebConfig.class) //You can use your xml too
    public class YourControllerTest extends AbstractTestNGSpringContextTests {
        @Autowired
        private WebApplicationContext wac;
    
        private MockMvc mockMvc;
    
    
        @Test
        public void getEmailVerificationTest() throws Exception {
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    
            this.mockMvc.perform(get("/home")
                    .accept(MediaType.ALL))
                    .andExpect(status().isOk())
                    .andExpect(view().name("home/index"));
        }
    }
    

    이것은 홈 페이지를 테스트하는 샘플 코드입니다. Beginner 인 경우 위에서 언급 한 오류가 발생합니다. 먼저 AbstractTestNGSpringContextTests와 this.mockMvc = MockMvcBuilders.webAppContextSetup (this.wac) .build ()가 확장되는지 확인합니다. 적절한 장소에있다.

    또 다른 한가지는 @BeforeMethod 주석을 사용하여 this.mockMvc = MockMvcBuilders.webAppContextSetup (this.wac) .build (); 각 모듈에. 아래처럼 @BeforeMethod를 추가해야합니다.

        @BeforeMethod
        public void setWac(){
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
        }
    
  4. ==============================

    4.설정에 대한 주석을 아래에 추가하십시오. @BeforeClass (dependsOnMethods = { "springTestContextPrepareTestInstance"})

    설정에 대한 주석을 아래에 추가하십시오. @BeforeClass (dependsOnMethods = { "springTestContextPrepareTestInstance"})

    romeara의 https://stackoverflow.com/a/16474433/2948001

  5. ==============================

    5.이런 식으로하려고 노력해라.

    이런 식으로하려고 노력해라.

    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.setup.MockMvcBuilders;
    import org.springframework.web.context.WebApplicationContext;
    
    import com.javainuse.test.SpringBootHelloWorldTests;
    
    public class TestControllerTest extends SpringBootHelloWorldTests {
    
        @Autowired
        private WebApplicationContext webApplicationContext;
    
        private MockMvc mockMvc;
    
        @Before
        public void setup() {
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        }
    
        @Test
        public void testEmployee() throws Exception {
            mockMvc.perform(get("/employee")).andExpect(status().isOk())
                    .andExpect(content().contentType("application/json;charset=UTF-8"))
                    .andExpect(jsonPath("$.name").value("emp1")).andExpect(jsonPath("$.designation").value("manager"))
                    .andExpect(jsonPath("$.empId").value("1")).andExpect(jsonPath("$.salary").value(3000));
    
        }
    
    }
    

    SpringBootHelloWorldTests는 다음과 같습니다.

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import com.javainuse.SpringBootHelloWorldApplication;
    
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes=SpringBootHelloWorldApplication.class)
    public class SpringBootHelloWorldTests {
    
        @Test
        public void contextLoads() {
        }
    
    }
    

    이것이 SpringBootHelloWorldApplication입니다.

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SpringBootHelloWorldApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringBootHelloWorldApplication.class, args);
        }
    }
    
  6. from https://stackoverflow.com/questions/19135492/webapplicationcontext-doesnt-autowire by cc-by-sa and MIT license