【问题标题】:Error running JUnitWeb Test on Method setup在方法设置上运行 JUnitWeb 测试时出错
【发布时间】:2021-01-16 10:52:00
【问题描述】:

我有一个 Spring 应用程序, 我已经创建了这个测试:

@RunWith(SpringRunner.class)
@SpringJUnitWebConfig(locations = {
        "classpath:testDatabaseContext.xml",
        "classpath:testServicesContext.xml",
        "classpath:backoffice-servlet.xml"
})
public class UserControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @Before
    void setup(WebApplicationContext wac) {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
..
}

但是当我开始测试时,我得到了这个错误:

rg.junit.runners.model.InvalidTestClassError: Invalid test class 'com.pastis.UserControllerTests':
  1. Method setup() should be public
  2. Method setup should have no parameters

【问题讨论】:

    标签: java spring junit log4j dbunit


    【解决方案1】:

    这里是一个例子:

    RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(classes = MyWebConfig.class)
    public class CustomerControllerTest {
    
        @Autowired
        private WebApplicationContext wac;
    
        private MockMvc mockMvc;
    
        @Before
        public void setup () {
            DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
            this.mockMvc = builder.build();
        }
    
        @Test
        public void testUserController () throws Exception {
            ResultMatcher ok = MockMvcResultMatchers.status()
                                                    .isOk();
    
            MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/customers");
            this.mockMvc.perform(builder)
                        .andExpect(ok);
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      所以我解释一下异常的输出:

      1. 将修饰符 public 添加到您的方法设置中,否则 JUnit 无法调用它
      2. 从方法中删除参数,@Before、@After 等不允许参数。

      如何正确设置 MockMvc 是另一个问题。最近的 Spring 和关于 web 范围初始化和 -behavior 的附加注释离开了这个答案的范围。 (这也需要进一步澄清,例如哪个 JDK、哪个 Spring 或 Spring Boot……XML 配置、dbunit 和 JUnit 4 建议使用遗留上下文。)

      【讨论】:

        猜你喜欢
        • 2014-06-28
        • 1970-01-01
        • 1970-01-01
        • 2014-08-07
        • 1970-01-01
        • 2013-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多