網(wǎng)站開發(fā)億瑪酷技術(shù)做seo有什么好處
????????在平常的開發(fā)工作中,我們經(jīng)常需要寫單元測試。比如,我們有一個校驗接口,可能會返回多種錯誤信息。我們可以針對這個接口,寫多個單元測試方法,然后將其場景覆蓋全。那么,怎么才能寫一個測試方法,就將其涉及到的場景測試全呢?
????????1:例如:有一個校驗身份證號的接口,涉及業(yè)務(wù)場景:身份證號為空校驗,身份證號是否正確。那么在單元測試的時候,需要測試身份證號為空的數(shù)據(jù)、身份證號格式錯誤的數(shù)據(jù)和身份證號格式正確的數(shù)據(jù)。
? ? ? ? 2:業(yè)務(wù)代碼實現(xiàn):
package test.boot.service.impl;import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import test.boot.dao.StudentDao;
import test.boot.service.StudentService;
import test.boot.vo.StuentVO;@Service
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentDao studentDao;public String checkIdNo(String idNo) {String regex = "^\\d{17}[0-9Xx]$";if (StringUtils.isBlank(idNo)) {return "身份證號為空";}if (idNo.matches(regex)) {return "身份證號格式正確";} else {return "身份證號格式錯誤";}}}
????????3:涉及三種場景,單元測試怎么寫呢?可能我們會寫三個單元測試的方法,如下:
@Test
public void testCheckIdNoEmpty() {String result = new StudentServiceImpl().checkIdNo("");Assert.assertEquals("身份證號為空", result);
}
@Test
public void testCheckIdNoFormatSuc() {String result = new StudentServiceImpl().checkIdNo("666777199911112222");Assert.assertEquals("身份證號格式正確", result);
}
@Test
public void testCheckIdNoFormatError() {String result = new StudentServiceImpl().checkIdNo("345678889");Assert.assertEquals("身份證號格式錯誤", result);
}
????????4:上述寫法沒有任何問題,如果我們需要測很多個接口,涉及到的業(yè)務(wù)場景有很多,那么看單元測試的時候,很難發(fā)現(xiàn)場景是否覆蓋完全,那么我們是否可以優(yōu)化為一個方法呢?如下:使用 @ParameterizedTest 和 @CsvSource 注解,@ParameterizedTest表示參數(shù)注冊,也表示單元測試,@ParameterizedTest 和 @Test不能同時使用,@CsvSource 表示多參數(shù)注解,可以用分隔符分割數(shù)據(jù)。
????????5:使用?@ParameterizedTest 和 @CsvSource 注解,可以用一個方法,即可測所有場景,我們可以傳入兩個參數(shù),一個是身份證號,一個是預(yù)期結(jié)果。代碼如下:
@ParameterizedTest
@CsvSource({"'', '身份證號為空'","'610222199911115511', '身份證號格式正確'","'61022219991111551X', '身份證號格式正確'","'6102221999111', '身份證號格式錯誤'"})
public void testCheckIdNo(String idNo, String expected) {StudentService studentService = new StudentServiceImpl();String result = studentService.checkIdNo(idNo);Assert.assertEquals(expected, result);
}
執(zhí)行結(jié)果:
? ? ? ? 不斷的學(xué)習(xí),才能讓自己變得更好!美好的風(fēng)景一直在路上,加油!