天天看點

Junit單元測試使用

Junit單元測試使用

    • 1.簡單測試
    • 2.DAO未完成時的測試
    • 3.測試方法
    • 4.覆寫率檢視

1.簡單測試

先建立springBoot項目,選擇javaWeb進行建立

建立實體類、DAO、Service

實體類

public class Student {
    private int id;
    private int age;
    private String name;
    public Student(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

           

對應的DAO類

import com.zxm.mockito.domain.Student;
import org.springframework.stereotype.Component;
@Component
public class StudentDao {
    public Student getStudentById(int id){
        return new Student(id,10,"Tony");
    }
}
           

對應的Service類

import com.zxm.mockito.dao.StudentDao;
import com.zxm.mockito.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StudentService {
    @Autowired
    StudentDao studentDao;
    public Student getStudentById(int id){
        return studentDao.getStudentById(id);
    }

}
           

對需要測試的類,按ctrl + shift +T,生成測試類

Junit單元測試使用

或者滑鼠右鍵Generate再選擇test

Junit單元測試使用

接下來就是選擇好測試的方法

Junit單元測試使用

在測試類裡進行方法測試的内容,該類用于測試一般不需要公開,對測試類添加@SpringBootTest注解,再@Autowired自動裝配StudentService對象

@Test
    void getStudentById() {
        Student student =studentService.getStudentById(1);
        Assertions.assertNotNull(student);
        Assertions.assertEquals(18,student.getAge());
        Assertions.assertEquals("cattle",student.getName());
       
        //lambda表達式一次檢測全部的斷言
        //Assertions.assertAll(()->Assertions.assertNull(student),
                            //()->Assertions.assertEquals(12,student.getAge()),
                            //()->Assertions.assertEquals("Tom",student.getName())
                           // );
  
    }
           

lamda表達式的檢視,第一個是期望參數,第二個是實際參數

Junit單元測試使用

2.DAO未完成時的測試

用Mockito執行when方法傳回Mock資料,在when裡的方法執行前傳回一個對象

MockBean的作用:建立一個虛拟的對象替代那些不易構造或不易擷取的對象。

@MockBean
    StudentDao studentDao;
    @BeforeEach
    void setUp(){
        Mockito.when(studentDao.getStudentById(1)).thenReturn(new Student(1,18,"cattle"));
    }
           

再進行上面方法測試。

3.測試方法

假設測試,Assumptions.assumeTrue()隻有假設成立才進行斷言,否則忽略或跳過

@Test
    @DisplayName("Should only run test if some criteria are met")
    void shouldOnlyRun(){
        Assumptions.assumeTrue(20<10);
        Assertions.assertEquals(1,1);
    }
           

資料驅動測試,将ValueSource裡的資料都帶入參數進行測試

//資料驅動測試
    @ParameterizedTest(name="{0}")
    @DisplayName("should create shapes with different number of size")
    @ValueSource(ints={3,5,4,9,7,8})
    void shouldCreateShape(int expectedInt){
        List<Integer> list =new ArrayList<Integer>();
        list.add(0,expectedInt);
        Assertions.assertEquals(expectedInt,list.get(0));
    }
           

異常值檢測,所有ValueSource的值都需要異常抛出才能正常通過

//無效值異常檢測
    @ParameterizedTest
    @DisplayName("check invalid nums")
    @ValueSource(ints={-1,0,2,Integer.MAX_VALUE})
    void checkInvalidNums(int expectedInt){

        Assertions.assertThrows(IllegalArgumentException.class,
                ()->normalNums(expectedInt));
    }
    //檢測方法
    public void normalNums(int num){
        if(num<=0||num==Integer.MAX_VALUE){
            throw new IllegalArgumentException();
        }
    }
           

嵌套測試,對多個相似或不同的子產品進行測試,@Nested對類進行嵌套說明。

assertNotSame與assertNotEquals不同,後者更擅長對比數字和boolean值,前者的語義要求更嚴格一些

//嵌套測試  相似的類進行串聯測試
    @Nested
    @DisplayName("Whem a List has been create")
    class WhenListCreate{
        private final List<Integer> list=new ArrayList<>();
        @Nested
        @DisplayName("Should allow")
        class ShouldAllow{
            @Test
            @DisplayName("See the size")
            void seeTheSide(){
                Assertions.assertEquals(0,list.size());
            }

            @Test
            @DisplayName("See the description")
            void seeTheDescription(){
                Assertions.assertEquals("[]",list.toString());
            }
        }


        @Nested
        @DisplayName("Should not allow")
        class ShouldNotAllow{
            @Test
            @DisplayName("be equal to another list with the same size")
            void beEqualAnotherList(){
                Assertions.assertNotSame(new ArrayList<String>(),list);
            }
        }
    }
           

4.覆寫率檢視

在整個項目目錄上右鍵選擇測試覆寫,

Junit單元測試使用

從自己的包中找到對應的類

Junit單元測試使用

每個包對應的類的覆寫率、方法覆寫率、行覆寫率都可以檢視

Junit單元測試使用

繼續閱讀