CharLemAznable / blog

When I was young, I used to think that money was the most important thing in life, now that I am old, I know it is.
MIT License
4 stars 0 forks source link

使用JUnit5进行Spring Controller/Interceptor/Filter单元测试 #4

Open CharLemAznable opened 5 years ago

CharLemAznable commented 5 years ago
添加maven依赖
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>${junit-jupiter.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>${junit-jupiter.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
    <scope>test</scope>
</dependency>
单元测试类添加注解
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = YourConfiguration.class)
@WebAppConfiguration // 标注为WebApp测试
@TestInstance(Lifecycle.PER_CLASS) // 为在@BeforeAll方法中使用自动注入的Bean, 方法需为非static, 测试类需添加此注解
public class YourTest {
// ...
}
初始化MockMvc
private static MockMvc mockMvc;

@BeforeAll
public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(yourController) // 可添加多个Controller
            .addMappedInterceptors(new String[]{"/**"}, yourInterceptor)
            .addFilters(yourFilter).build();
}
单元测试用例
@Test
public void testSample() {
    val response = mockMvc.perform(MockMvcRequestBuilders.get("/your-req-path")
            .param("key", "value"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn().getResponse();
    // some assertions
}
CharLemAznable commented 5 years ago

使用WebApplicationContext初始化MockMvc

YourConfiguration添加EnableWebMvc注解
@EnableWebMvc // IMPORTANT
@ComponentScan
@Configuration
public class YourConfiguration implements WebMvcConfigurer {

    @Autowired
    private YourInterceptor yourInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(yourInterceptor).addPathPatterns("/**");
    }
}
初始化MockMvc
private static MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;

@BeforeAll
public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
            .addFilters(yourFilter).build();
}