欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java學(xué)習(xí)之junit單元測試案例(經(jīng)典版)

 更新時間:2024年12月25日 08:51:39   作者:健康平安的活著  
這篇文章主要介紹了java學(xué)習(xí)之junit單元測試的相關(guān)資料,文中講解了JUnit單元測試的基本概念、作用、使用assert進(jìn)行驗證、覆蓋率分析、BeforeEach和AfterAll的使用、通過反射和注解實現(xiàn)測試,需要的朋友可以參考下

一  junit單元測試

1.1 單元測試作用

單元測試要滿足AIR原則,即

A: automatic 自動化;

I: Independent  獨立性;

R:Repeatable 可重復(fù);

2.單元測試必須使用assert來驗證

1.2 案例1 常規(guī)單元測試

1.代碼

public class CalcDemo
{
    public int add(int x ,int y)
    {
        return x + y;
        //return x * y;
    }

    public int sub(int x ,int y)
    {
        return x - y;
    }
}

2.測試

public class AppTest 

{
    @Test
    void sub()
    {
        CalcDemo calcDemo = new CalcDemo();
        int retValue = calcDemo.sub(2, 2);
        assertEquals(0,retValue);
        System.out.println("");
    }
}

1.3 案例2 單元覆蓋率Coverage*

1.代碼

public class ScoreDemo
{
    public String scoreLevel(int score)
    {
        if(score <= 0) {
            throw new IllegalArgumentException("缺考");
        } else if (score < 60) {
            return "弱";
        } else if (score < 70) {
            return "差";
        } else if (score <= 80) {
            return "中";
        } else if (score < 90) {
            return "良";
        } else {
            return "優(yōu)";
        }
    }
}

2.測試

class ScoreDemoTest
{
    @Test
    void scoreLevel()
    {
        ScoreDemo scoreDemo = new ScoreDemo();
        assertEquals("弱",scoreDemo.scoreLevel(52));
    }

    @Test
    void scoreLevelv2()
    {
        ScoreDemo scoreDemo = new ScoreDemo();
        assertEquals("差",scoreDemo.scoreLevel(62));
    }

    @Test
    void scoreLevelv3()
    {
        ScoreDemo scoreDemo = new ScoreDemo();
        assertEquals("中",scoreDemo.scoreLevel(80));
    }

    @Test
    void scoreLevelv4()
    {
        ScoreDemo scoreDemo = new ScoreDemo();
        assertThrows(IllegalArgumentException.class,() -> scoreDemo.scoreLevel(-7));
    }
}

查看測試報告:對應(yīng)覆蓋率

1.4 案例3 BeforeEach,BeforeAfterall

1.4.1 Api說明

1.4.2 案例操作 

1.代碼

public class CalcDemo
{
    public int add(int x ,int y)
    {
        return x + y;
        //return x * y;
    }

    public int sub(int x ,int y)
    {
        return x - y;
    }
}

2.測試 

class CalcDemoTestV2
{
    CalcDemo calcDemo = null;

    static StringBuffer stringBuffer = null;

    @BeforeAll
    static void m1()
    {
        stringBuffer = new StringBuffer("abc");
        System.out.println("===============: "+stringBuffer.length());
    }

    @AfterAll
    static void m2()
    {
        System.out.println("===============: "+stringBuffer.append(" ,end").toString());
    }



    @BeforeEach
    void setUp()
    {
        System.out.println("----come in BeforeEach");
        calcDemo = new CalcDemo();
    }

    @AfterEach
    void tearDown()
    {
        System.out.println("----come in AfterEach");
        calcDemo = null;
    }

    @Test
    void add()
    {
        assertEquals(5,calcDemo.add(1,4));
        assertEquals(5,calcDemo.add(2,3));
    }

    @Test
    void sub()
    {
        assertEquals(5,calcDemo.sub(10,5));
    }
}

3.結(jié)果

1.5 案例4  junit+反射+注解實現(xiàn)測試

1.定義注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AtguiguTest
{
}

2.定義調(diào)用類

public class CalcHelpDemo
{
    public int mul(int x ,int y)
    {
        return x * y;
    }

    @AtguiguTest
    public int div(int x ,int y)
    {
        return x / y;
    }
    @AtguiguTest
    public void thank(int x ,int y)
    {
        System.out.println("3ks,help me test bug");
    }
}

3.定義測試類

@Slf4j
public class AutoTestClient
{
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException
    {
        //家庭作業(yè),抽取一個方法,(class,p....)
        CalcHelpDemo calcHelpDemo = new CalcHelpDemo();
        int para1 = 10;
        int para2 = 0;


        Method[] methods = calcHelpDemo.getClass().getMethods();
        AtomicInteger bugCount = new AtomicInteger();
        // 要寫入的文件路徑(如果文件不存在,會創(chuàng)建該文件)
        String filePath = "BugReport"+ (DateUtil.format(new Date(), "yyyyMMddHHmmss"))+".txt";


        for (int i = 0; i < methods.length; i++)
        {
            if (methods[i].isAnnotationPresent(AtguiguTest.class))
            {
                try
                {
                    methods[i].invoke(calcHelpDemo,para1,para2);//放行
                } catch (Exception e) {
                    bugCount.getAndIncrement();
                    log.info("異常名稱:{},異常原因:{}",e.getCause().getClass().getSimpleName(),e.getCause().getMessage());


                    FileUtil.writeString(methods[i].getName()+"\t"+"出現(xiàn)了異常"+"\n", filePath, "UTF-8");
                    FileUtil.appendString("異常名稱:"+e.getCause().getClass().getSimpleName()+"\n", filePath, "UTF-8");
                    FileUtil.appendString("異常原因:"+e.getCause().getMessage()+"\n", filePath, "UTF-8");
                }finally {
                    FileUtil.appendString("異常數(shù):"+bugCount.get()+"\n", filePath, "UTF-8");
                }
            }
        }
    }
}

4.查看結(jié)果

1.6 案例5  web工程單元測試

1.6.1 mock和spy的區(qū)別聯(lián)系

1.6.2 案例

1.pom配置

   <!--test-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--test-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>

2.處理類

@Service
public class MemberService
{
    public String add(Integer uid)
    {
        System.out.println("---come in addUser,your uid is: "+uid);
        if (uid == -1)
        {
            throw new IllegalArgumentException("parameter is negative。。。。");
        }
        return "ok";
    }

    public int del(Integer uid)
    {
        System.out.println("---come in del,your uid is: "+uid);

        return uid;
    }
}

3.啟動類

@SpringBootApplication
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
        System.out.println( "Hello World!" );
    }
}

4.測試類

@SpringBootTest
public class MemberTest {
     @Resource //真實調(diào)用,落盤mysql-MQ=redis。。。。測試條件充分的情況下
    private MemberService memberService1;

//    @Test
//    void m1()
//    {
//        String result = memberService1.add(2);
//        assertEquals("ok",result);
//
//        System.out.println("----m1 over");
//    }

    @MockBean
    private MemberService memberService2;

//    @Test
//    void m2_NotMockRule()
//    {
//        String result = memberService2.add(2);
//        assertEquals("ok",result);
//
//        System.out.println("----m2_NotMockRule over");
//    }

//    @Test
//    void m2_WithMockRule()
//    {
//        when(memberService2.add(3)).thenReturn("ok");//不真的進(jìn)入數(shù)據(jù)庫/MQ,不落盤,改變return
//
//        String result = memberService2.add(3);
//        assertEquals("ok",result);
//
//        System.out.println("----m2_WithMockRule over");
//    }
@SpyBean //有規(guī)則按照規(guī)則走,沒有規(guī)則走真實
private MemberService memberService3;
    @Test
    void m3()
    {
        when(memberService3.add(2)).thenReturn("ok");
        String result = memberService3.add(2);
        System.out.println("----add result:  "+result);
        Assertions.assertEquals("ok",result);

        int result2 = memberService3.del(3);
        System.out.println("----del result2:  "+result2);
        Assertions.assertEquals(3,result2);

//跨部門調(diào)用,不是寫代碼,累的是心,協(xié)調(diào)工作。    zzyybs@126.com
        System.out.println("----over");
    }
}

4.結(jié)果

總結(jié) 

到此這篇關(guān)于java學(xué)習(xí)之junit單元測試的文章就介紹到這了,更多相關(guān)java junit單元測試案例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java反射通過Getter方法獲取對象VO的屬性值過程解析

    Java反射通過Getter方法獲取對象VO的屬性值過程解析

    這篇文章主要介紹了Java反射通過Getter方法獲取對象VO的屬性值過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02
  • SpringMVC自定義類型轉(zhuǎn)換器實現(xiàn)解析

    SpringMVC自定義類型轉(zhuǎn)換器實現(xiàn)解析

    這篇文章主要介紹了SpringMVC自定義類型轉(zhuǎn)換器實現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-12-12
  • springboot啟動時沒有日志的原因分析

    springboot啟動時沒有日志的原因分析

    這篇文章主要介紹了springboot啟動時沒有日志的原因分析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • spring MVC中傳遞對象參數(shù)示例詳解

    spring MVC中傳遞對象參數(shù)示例詳解

    這篇文章主要給大家介紹了在spring MVC中傳遞對象參數(shù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看吧。
    2017-06-06
  • IntelliJ IDEA 詳細(xì)圖解最常用的配置(適合剛剛用的新人)

    IntelliJ IDEA 詳細(xì)圖解最常用的配置(適合剛剛用的新人)

    這篇文章主要介紹了IntelliJ IDEA 詳細(xì)圖解最常用的配置,本篇教程非常適合剛剛用的新人,本文圖文并茂給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • Java中的Future獲取任務(wù)返回值詳解

    Java中的Future獲取任務(wù)返回值詳解

    這篇文章主要介紹了Java中的Future獲取任務(wù)返回值詳解,在向線程池ThreadPoolExecutor提交任務(wù)時,一般為了方便操作采用execute提交任務(wù),這時線程其實是無返回值的,需要的朋友可以參考下
    2023-12-12
  • Ubuntu快速安裝jdk的教程

    Ubuntu快速安裝jdk的教程

    這篇文章主要為大家詳細(xì)介紹了Ubuntu快速安裝jdk的教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • Java實現(xiàn)去除文檔陰影的示例代碼

    Java實現(xiàn)去除文檔陰影的示例代碼

    文稿掃描大家用的都比較頻繁、想是各種證件、文件都可以通過掃描文稿功能保存到手機(jī)。相比直接拍照,在掃描文稿時,程序會對圖像進(jìn)行一些矯正。比如去除陰影、修正傾斜、旋轉(zhuǎn)矯正等。進(jìn)行這些處理后的圖片要更加容易識別。今天就來討論一下去除陰影的操作
    2022-12-12
  • 一篇文章帶你了解Java SpringBoot Nacos

    一篇文章帶你了解Java SpringBoot Nacos

    這篇文章主要介紹了SpringBoot使用Nacos配置中心的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-09-09
  • java生成驗證碼工具類

    java生成驗證碼工具類

    這篇文章主要為大家詳細(xì)介紹了java生成驗證碼工具類,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-03-03

最新評論