最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2024年12月25日 08:51:39   作者:健康平安的活著  
這篇文章主要介紹了java學(xué)習(xí)之junit單元測試的相關(guān)資料,文中講解了JUnit單元測試的基本概念、作用、使用assert進行驗證、覆蓋率分析、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");//不真的進入數(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)文章

  • scala中常用特殊符號詳解

    scala中常用特殊符號詳解

    這篇文章主要介紹了scala中常用特殊符號詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • Python爬蟲 12306搶票開源代碼過程詳解

    Python爬蟲 12306搶票開源代碼過程詳解

    這篇文章主要介紹了Python爬蟲 12306搶票開源代碼過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • Java基于迭代器模式實現(xiàn)的訪問人員列表操作示例

    Java基于迭代器模式實現(xiàn)的訪問人員列表操作示例

    這篇文章主要介紹了Java基于迭代器模式實現(xiàn)的訪問人員列表操作,簡單描述了迭代器模式的概念、原理以及使用迭代器模式實現(xiàn)訪問人員列表的相關(guān)操作技巧,需要的朋友可以參考下
    2018-05-05
  • Java多線程處理List問題

    Java多線程處理List問題

    這篇文章主要介紹了Java多線程處理List問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • java面試常見模式問題---代理模式

    java面試常見模式問題---代理模式

    代理模式是常用的java設(shè)計模式,他的特征是代理類與委托類有同樣的接口,代理類主要負責(zé)為委托類預(yù)處理消息、過濾消息、把消息轉(zhuǎn)發(fā)給委托類,以及事后處理消息
    2021-06-06
  • SpringBoot項目引入token設(shè)置方式

    SpringBoot項目引入token設(shè)置方式

    本文詳細介紹了JWT(JSON Web Token)的基本概念、結(jié)構(gòu)、應(yīng)用場景以及工作原理,通過動手實踐,展示了如何在Spring Boot項目中實現(xiàn)JWT的生成、驗證和攔截器配置
    2025-01-01
  • Java之打印String對象的地址

    Java之打印String對象的地址

    這篇文章主要介紹了Java之打印String對象的地址,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Java循環(huán)調(diào)用多個timer實現(xiàn)定時任務(wù)

    Java循環(huán)調(diào)用多個timer實現(xiàn)定時任務(wù)

    這篇文章主要介紹了Java循環(huán)調(diào)用多個timer實現(xiàn)定時任務(wù),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • Java排序算法之選擇排序

    Java排序算法之選擇排序

    這篇文章主要介紹了Java排序算法之選擇排序,文中有非常詳細的代碼示例,對正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下
    2021-05-05
  • Java設(shè)計模式中的簡單工廠模式解析

    Java設(shè)計模式中的簡單工廠模式解析

    這篇文章主要介紹了Java設(shè)計模式中的簡單工廠模式解析,簡單工廠模式提供一個創(chuàng)建對象實例的功能,而無須關(guān)心其具體實現(xiàn),被創(chuàng)建實例的類型可以是接口、抽象類,也可以是具體的類,需要的朋友可以參考下
    2023-11-11

最新評論

巴彦淖尔市| 睢宁县| 曲松县| 信宜市| 邯郸县| 罗山县| 桂林市| 大埔区| 怀安县| 滦南县| 安溪县| 荆州市| 四川省| 岗巴县| 沙田区| 博白县| 彭州市| 碌曲县| 外汇| 石楼县| 建瓯市| 鄂伦春自治旗| 北海市| 枝江市| 永济市| 高邑县| 图们市| 兴和县| 湾仔区| 佛山市| 长乐市| 潜山县| 阿拉善左旗| 云南省| 宿州市| 五家渠市| 普格县| 民勤县| 马龙县| 绥中县| 南投市|