spring-boot-單元測試參數數


簡單案例

@RunWith(Parameterized.class)
public class ParameterTest {
    // 2.聲明變量存放預期值和測試數據
    private String firstName;
    private String lastName;

    //3.聲明一個返回值 為Collection的公共靜態方法,並使用@Parameters進行修飾
    @Parameterized.Parameters
    public static List<Object[]> param() {
        // 這里我給出兩個測試用例
        return Arrays.asList(new Object[][]{{"Mike", "Black"}, {"Cilcln", "Smith"}});
    }

    //4.為測試類聲明一個帶有參數的公共構造函數,並在其中為之聲明變量賦值
    public ParameterTest(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    // 5. 進行測試,發現它會將所有的測試用例測試一遍
    @Test
    public void test() {
        String name = firstName + " " + lastName;
        System.out.println(name);
        assertThat("Mike Black", is(name));
    }


}

參數化在 測試controller 中的應用

@RunWith(Parameterized.class)
@SpringBootTest
public class LearnController14Test {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mvc;

    private MockHttpSession session;


    public Long id;
    public String title;

    public LearnController14Test(Long id, String title) {
        super();
        this.id = id;
        this.title = title;
    }

    /**
     * 這些參數,都會測試一遍
     *
     * @return
     */
    @Parameterized.Parameters
    public static List<Object[]> data() {
        return Arrays.asList(new Object[][]{{999L, "Black"}, {997L, "Smith"}});
    }


    @Before
    public void setupMockMvc() throws Exception {
        //借助TestContextManager來實現上下文注入
        TestContextManager testContextManager = new TestContextManager(getClass());
        testContextManager.prepareTestInstance(this);


        //初始化MockMvc對象
        mvc = MockMvcBuilders.webAppContextSetup(wac).build();

        //構建session
        session = new MockHttpSession();
        User user = new User("root", "root");
        //攔截器那邊會判斷用戶是否登錄,所以這里注入一個用戶
        session.setAttribute("user", user);
    }


    /**
     * 獲取教程測試用例
     * <p>
     * get 請求
     *
     * @throws Exception
     */
    @Test
    public void qryLearn() throws Exception {

        mvc.perform(MockMvcRequestBuilders.get("/learn/resource/" + id + "?title=" + title)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .session(session)
        )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print());
    }


}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM