如何使用Junit5测试Spring 5控制器 [英] How to test spring 5 controllers with Junit5

查看:275
本文介绍了如何使用Junit5测试Spring 5控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JUnit 5测试我的Spring 5 Web控制器. 测试控制器的两种方法(如spring文档中所述)总是给我空指针.

I'm trying to test my Spring 5 web controllers with JUnit 5. The two way to test controller (as mentionned in spring documentation) always give me null pointer.

这是我的考试班

import com.lacunasaurus.gamesexplorer.test.configuration.TestBackEndConfiguration;
import com.lacunasaurus.gamesexplorer.test.configuration.TestWebConfig;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

@RunWith(JUnitPlatform.class)
@ExtendWith(SpringExtension.class)
@WebAppConfiguration()
@ContextConfiguration(classes = {TestWebConfig.class, TestBackEndConfiguration.class})
public class TestAuthenticationCreateAccountController {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        // this.mockMvc = MockMvcBuilders.standaloneSetup(new AuthenticationCreateAccountController()).build();

        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void getAccount() throws Exception {
        // Here i've got an null pointer
        mockMvc.perform(get("/"));
    }

}

这是我用于测试的Web配置

Here my web configuration for tests

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@ComponentScan(basePackages = {"com.lacunasaurus.gamesexplorer.web"})
public class TestWebConfig implements WebMvcConfigurer, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}

现在是我的控制器

  @Controller
  @RequestMapping("/create-account")
  public class AuthenticationCreateAccountController {

   @Autowired
   UserAccountValidator accountValidator;

   @Autowired
   AuthenticationService authenticationService;

   @GetMapping
   public String navigate() {
       return "authentication/create-account";
   }

   @ModelAttribute("userAccount")
   public UserAccount setDefaultAccount() {

       return new UserAccount();
   }

   @InitBinder
   protected void initBinder(WebDataBinder binder) {

       binder.addValidators(accountValidator);
   }

   @PostMapping
   public String createAccount(@Validated UserAccount userAccount, BindingResult bindingResult) {

       if (bindingResult.hasErrors()) {
           return "authentication/create-account";
       }

       authenticationService.createUserAccount(userAccount);

       return "authentication/create-account";
   }
  }

IDE给出的堆栈跟踪

  java.lang.NullPointerException at com.lacunasaurus.gamesexplorer.test.controller.TestAuthenticationCreateAccountController.getAccount(TestAuthenticationCreateAccountController.java:41)

Results :

Tests in error: 
    TestAuthenticationCreateAccountController.getAccount:41 NullPointer

我已经用junit 5和spring测试了我的后端,一切正常.

I've got already test my backend with junit 5 and spring and everything work well.

感谢那些可以帮助我了解如何测试控制器的人:)

Thanks to thoses who will help me to understand how to test controller :)

推荐答案

控制器的新测试:

@ExtendWith(SpringExtension.class)
@WebAppConfiguration()
@ContextConfiguration(classes = {TestWebConfig.class, TestBackEndConfiguration.class})
@TestInstance(Lifecycle.PER_CLASS)
public class TestAuthenticationCreateAccountController {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

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

    @Test
    void getAccount() throws Exception {
        mockMvc.perform(get("/toto")).andExpect(status().isOk());
    }

}

这篇关于如何使用Junit5测试Spring 5控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆