1. 程式人生 > >SpringBoot進階之單元測試

SpringBoot進階之單元測試

1.測試方法

service程式碼

public Girl findOne(Integer id){
    return girlRepository.findOne(id);   //通過id查詢使用者資訊
}

serviceTest程式碼
@RunWith(SpringRunner.class)    //表示要在測試環境執行
@SpringBootTest            // 表示將啟動這個SpringBoot工程
public class GirlServiceTest {

    @Autowired
    private GirlService girlService;

    @Test
    public void findOneTest(){
        Girl girl =girlService.findOne(22);     //查詢id為22的使用者的資訊
        //斷言
        Assert.assertEquals(new Integer(18),girl.getAge());   //使用斷言判斷id為22的使用者的年齡是否為18
    }
}

執行測試 步驟  :

   選中 findOneTest方法名  右擊選擇 Run'findOneTest()'執行


測試通過圖


測試失敗圖:表示 id為22的使用者的年齡實際值是18但是測試中的值卻是16 異常


2.測試介面

ControllerTest程式碼

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GirlControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testGirlList() throws Exception{
      mockMvc.perform(MockMvcRequestBuilders.get("/girls"))         //訪問/girls介面
              .andExpect(MockMvcResultMatchers.status().isOk());
              // .andExpect(MockMvcResultMatchers.content().string("abc"));  //判斷訪問介面返回資料是不是abc
    }
}

執行方法與測試方法一樣