WebApplicationContext不会自动装配

时间:2013-10-02 11:06:11

标签: java spring testing spring-mvc

我写这个测试类:

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

7 个答案:

答案 0 :(得分:12)

除非您将WebApplicationContext添加到测试类中,否则ApplicationContext只有@WebAppConfiguration

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

除了@RunWith注释,您还可以扩展一个spring便捷类。

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

链接

  1. WebAppConfiguration javadoc
  2. Reference Guide

答案 1 :(得分:11)

我使用TestNG&amp; amp;的Mockito。

事实证明wac不是自动装配的,并且在@BeforeTest方法中可用但是在@Test方法中。

我感动了这个

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

到@Test方法和presto,它可以工作!

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

答案 2 :(得分:2)

WebApplicationContext is requiredNullPointerException是我作为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"));
    }
}

这是测试主页的示例代码。如果您是初学者,则会出现上述错误,请先检查extends AbstractTestNGSpringContextTeststhis.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();
    }

答案 3 :(得分:1)

尝试这样做

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

答案 4 :(得分:0)

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

罗马拉的

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

答案 5 :(得分:0)

对我来说,这个问题没有以下maven依赖项:

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

但是我正在这样注入上下文:

@Inject
protected WebApplicationContext webApplicationContext;
protected MockMvc mockMvc;

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

答案 6 :(得分:-1)

对我来说,添加RunWith注释后,该问题已解决。请看下面: @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,classes = {SampleConfig.class}) 公共类SampleTest {