SpringBoot进行参数化单元测试

背景:

SpringBoot:2.1.9

Jdk:1.8

进行单元测试的时候,要测试多组数据,需要对测试数据进行参数化。

 

方案:加载Spring主要靠@Before方法

@SpringBootTest
@RunWith(Parameterized.class)
public class BaseServiceTest {
    private String data;
    private String key;

    public BaseServiceTest(String data, String key) {
        this.data = data;
        this.key = key;
    }

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

    /**
     * 准备数据

     * @return
     */
    @Parameterized.Parameters
    public static Collection prepareData() {
        String[] pool = new String[]{"password", "hellohellohellohellohellohelloab", "hellohellohellohellohellohelloabc"};
        Collection datas = new ArrayList<>(9);

        for (String outer : pool) {
            for (String inner : pool) {
                datas.add(new String[]{outer, inner});
            }
        }
        return datas;
    }

    @Test
    public void test() {
        System.out.println("data:" + data + ", key:" + key);
    }
}

 

你可能感兴趣的:(spring)