How to test spring 5 controllers with Junit5

对着背影说爱祢 提交于 2020-01-03 11:15:43

问题


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.

This is my test class

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

}

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

}

And now my controller

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

EDIT : The stacktrace given by the IDE

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

Results :

Tests in error: 
    TestAuthenticationCreateAccountController.getAccount:41 NullPointer

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


回答1:


The new test for controllers :

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

}



回答2:


In order to use JUnit Jupiter, you must use autoconfigure MockMvc. This is a help to resolve all related configuration.

@ExtendWith(SpringExtension.class)
@WebAppConfiguration()
@AutoConfigureMockMvc


来源:https://stackoverflow.com/questions/49096577/how-to-test-spring-5-controllers-with-junit5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!