Java WebApplicationContext 不会自动装配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19135492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:25:03  来源:igfitidea点击:

WebApplicationContext doesn't autowire

javaspringtestingspring-mvc

提问by gstackoverflow

I write this test class :

我写了这个测试类:

@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();
         }
    }

But:

但:

After code execution I see next trace:

代码执行后,我看到下一个跟踪:

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.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.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access
@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();

    }
...
}
0(ParentRunner.java:42) at org.junit.runners.ParentRunner.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)

What Would I do for fixing my problem?

我会怎么做才能解决我的问题?

UPDATE

更新

I change code:

我更改代码:

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.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.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access
@ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class CandidateControllerTest { ... }
0(ParentRunner.java:42) at org.junit.runners.ParentRunner.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)

trace:

痕迹:

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

采纳答案by M. Deinum

There is no WebApplicationContextonly an ApplicationContextunless you add the @WebAppConfigurationto your test class.

没有WebApplicationContext唯一的ApplicationContext,除非你添加@WebAppConfiguration到您的测试类。

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

Instead of the @RunWithannotation you can also extend one of springs convenience classes.

除了@RunWith注解,您还可以扩展 springs 便利类之一。

@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"));
    }
}

Links

链接

  1. WebAppConfiguration javadoc
  2. Reference Guide
  1. WebApp 配置javadoc
  2. 参考指南

回答by obi1

I had the same issue using TestNG & Mockito.

我在使用 TestNG 和 Mockito 时遇到了同样的问题。

Turns out wac isn't autowired and available in @BeforeTest methods but is in @Test methods.

原来 wac 不是自动装配的,并且在 @BeforeTest 方法中可用,而是在 @Test 方法中。

I moved this

我移动了这个

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

to an @Test method and presto, it works!

到@Test 方法和presto,它的工作原理!

Here's the link I found with the solution: http://forum.spring.io/forum/spring-projects/web/737624-problem-with-autowiring-webapplicationcontext-with-annotationconfigcontextloader

这是我找到的解决方案链接:http: //forum.spring.io/forum/spring-projects/web/737624-problem-with-autowiring-webapplicationcontext-with-annotationconfigcontextloader

回答by user2948001

Add below annotation for your setup. @BeforeClass(dependsOnMethods={"springTestContextPrepareTestInstance"})

为您的设置添加以下注释。@BeforeClass(dependsOnMethods={"springTestContextPrepareTestInstance"})

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

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

回答by Menuka Ishan

WebApplicationContext is requiredand NullPointerExceptionare the most confusing errors I faced as beginner to TestNG and Spring Test Framework. These are happened due to simple mistakes like forget to `extends AbstractTestNGSpringContextTests1 etc. To avoid those errors I'll give you the code template I use.

WebApplicationContext is required并且NullPointerException是我作为 TestNG 和 Spring 测试框架的初学者遇到的最令人困惑的错误。这些是由于简单的错误而发生的,比如忘记`extends AbstractTestNGSpringContextTests1 等。为了避免这些错误,我会给你我使用的代码模板。

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));

    }

}

This is sample code to test home page. If you are Beginner, an error occur such as I mentioned above, first check whether extends AbstractTestNGSpringContextTestsand this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();are in the proper places.

这是测试主页的示例代码。如果您是初学者,出现我上面提到的错误,请先检查extends AbstractTestNGSpringContextTeststhis.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();是否在正确的位置。

Another thing is you can use @BeforeMethod annotation to stop repeating this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();in each module. You should have add @BeforeMethodlike Below.

另一件事是您可以使用 @BeforeMethod 注释来停止this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();在每个模块中重复。你应该@BeforeMethod像下面这样添加。

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() {
    }

}

回答by Bhaskara Arani

try to do like this

尝试这样做

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);
    }
}

and the SpringBootHelloWorldTests is as below

和 SpringBootHelloWorldTests 如下

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
        <scope>test</scope>
    </dependency>

and this is the SpringBootHelloWorldApplication

这是 SpringBootHelloWorldApplication

@Inject
protected WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;

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

回答by piotr szybicki

For me the issue was not having the following maven dependencies:

对我来说,问题不在于以下 Maven 依赖项:

##代码##

But I was injecting the context like this:

但我是这样注入上下文的:

##代码##

回答by NoviceCoder

For me the issue was resolved when I added the RunWith annotation. Please see below: @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,classes = {SampleConfig.class}) public class SampleTest {

对我来说,当我添加 RunWith 注释时,问题得到了解决。请看下面:@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,classes = {SampleConfig.class}) public class SampleTest {