由于Spring测试类上只能有一个@Runwith注解,如果使用@RunWith(Parameterized.class),就无法s使用@RunWith(SpringJUnit4ClassRunner.class)。

@RunWith(SpringJUnit4ClassRunner.class)是JUnit的注解,通过这个注解让SpringJUnit4ClassRunner
这个类提供Spring测试上下文

需要借助TestContextManager来实现上下文注入。

TestContextManager 与@RunWith(SpringJUnit4ClassRunner.class) 效果一样  

在spring-framework-reference中的介绍

Spring Boot Junit4 参数化测试Controller_spring

可以参考如下文章,利用TestContextManager来注入 Spring

参考如下java Code Examples for org.springframework.test.context.TestContextManager.prepareTestInstance


示例如下:

package com.netease.ey.pay.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import javax.annotation.Resource;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

@RunWith(Parameterized.class)
@SpringBootTest
@ContextConfiguration
@AutoConfigureMockMvc
public class PayControllerTest {
    private static final Logger logger = LoggerFactory.getLogger(PayControllerTest.class);

    @Resource
    private MockMvc mockMvc;

    private TestContextManager testContextManager;

    @Before
    public void setUp() throws Exception {
        testContextManager = new TestContextManager(getClass());
        testContextManager.prepareTestInstance(this);
    }


    @Parameterized.Parameters(name = "{index}:orderId:{0}")
    public static Object[] data() {
        return new Object[] { "1","7"};
    }
    @Parameterized.Parameter // first data value (0) is default
    public /* 不能为 private */ String orderId;

    @Test
    public void transfer() throws Exception {
        String response = mockMvc.perform(MockMvcRequestBuilders.post("/pay/transfer")
                .param("orderId", orderId))
                .andExpect(MockMvcResultMatchers.status().isOk()).andDo(print())         //打印出请求和相应的内容
                .andReturn().getResponse().getContentAsString();
        logger.info("返回值{}",response);

    }
}