13

我写了这个测试类:

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

7 回答 7

14

除非您将其添加到测试类中,否则WebApplicationContext不仅只有一个。ApplicationContext@WebAppConfiguration

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

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

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

链接

  1. WebAppConfiguration javadoc
  2. 参考指南
于 2013-10-02T11:16:57.603 回答
12

我在使用 TestNG 和 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

于 2014-06-19T19:14:24.663 回答
1

WebApplicationContext is required并且NullPointerException是我作为 TestNG 和 Spring 测试框架的初学者所面临的最令人困惑的错误。这些是由于简单的错误而发生的,例如忘记扩展 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();
    }
于 2017-01-13T04:38:33.317 回答
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();
}
于 2019-09-11T11:47:09.837 回答
0

尝试这样做

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);
    }
}
于 2019-01-19T19:01:54.930 回答
-1

为您的设置添加以下注释。

@BeforeClass(dependsOnMethods={"springTestContextPrepareTestInstance"})

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

于 2016-06-10T02:54:07.067 回答
-2

对我来说,当我添加 RunWith 注释时,问题就解决了。请看下面:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,classes = {SampleConfig.class})
public class SampleTest {
于 2019-12-26T19:40:02.673 回答