zoukankan      html  css  js  c++  java
  • Junit入门

    • 什么是Junit

     JUnit是一个Java语言的单元测试框架。通常我们写完代码想要测试这段代码的正确性,那么必须新建一个类,创建一个 main() 方法编写测试代码。如果需要测试的代码很多,就要将测试代码全部写在一个 main() 方法里面大大增加了测试的复杂度。而 Junit 能很好的解决这个问题,简化单元测试,写一点测一点,在编写以后的代码中如果发现问题可以较快的追踪到问题的原因,减小回归错误的纠错难度。

    • Junit安装

    1.下载 Junit jar 包

      百度网盘:点我下载   提取码:ojbo

    2.下载完成之后,在项目中将 下载的 jar 包导入进去,然后右键,Build--->Add Build Path--->Add External JARs  即可。

    • Junit常用注解

      1.@Test: 测试方法

        a)(expected=XXException.class)如果程序的异常和XXException.class一样,则测试通过
        b)(timeout=100)如果程序的执行能在100毫秒之内完成,则测试通过

      2.@Ignore: 被忽略的测试方法:加上之后,暂时不运行此段代码

      3.@Before: 每一个测试方法之前运行

      4.@After: 每一个测试方法之后运行

      5.@BeforeClass: 方法必须必须要是静态方法(static 声明),所有测试开始之前运行,注意区分before,是所有测试方法

      6.@AfterClass: 方法必须要是静态方法(static 声明),所有测试结束之后运行,注意区分 @After

    • 编写代码
     1 public class Calculator{
     2     
     3     public int add(int a,int b){
     4         
     5         return a+b;
     6     }
     7     
     8     public int sub(int a,int b){
     9         
    10         return a-b;
    11     }
    12     
    13     public int mul(int a,int b){
    14         
    15         return a*b;
    16     }
    17     
    18     public int div(int a,int b){
    19         
    20         return a/b;
    21     }
    22 }
    • 编写测试代码
     1 public class CalculatorTest {
     2 
     3     Calculator c = null;
     4     
     5     @Before
     6     public void setup(){
     7         c = new Calculator();
     8     }
     9     @Test
    10     public void testAdd() {
    11         int result = c.add(1, 2);
    12         Assert.assertEquals(result, 3);
    13     }
    14     @Test
    15     public void testSub() {
    16         int result = c.sub(1, 2);
    17         Assert.assertEquals(result, -1);
    18     }
    19     @Test
    20     public void testMul() {
    21         int result = c.mul(1, 2);
    22         Assert.assertEquals(result, 2);
    23     }
    24     @Test
    25     public void testDiv() {
    26         int result = c.div(2, 1);
    27         Assert.assertEquals(result, 2);
    28     }
    29 
    30 }
    • 测试结果

    结果出现如下的绿色横条,则测试通过,红色横条,则测试失败

  • 相关阅读:
    代理模式与Android
    图数据库 Titan 高速入门
    怎样编写支持命令行选项的程序
    协方差的意义
    我所理解的Spring AOP的基本概念
    Google搜索解析
    POJ 3311 Hie with the Pie floyd+状压DP
    JS怎样将拖拉事件与点击事件分离?
    C++语言笔记系列之十二——C++的继承
    Mac下Android配置及unity3d的导出Android
  • 原文地址:https://www.cnblogs.com/mxj961116/p/10693254.html
Copyright © 2011-2022 走看看