JUnit4单元测试的两种形式

特点:

  • JUnit 是一个开放的资源框架,用于编写和运行测试。

  • 提供注释来识别测试方法。

  • 提供断言来测试预期结果。

  • 提供测试运行来运行测试。

  • JUnit 测试允许你编写代码更快,并能提高质量。

  • JUnit 优雅简洁。没那么复杂,花费时间较少。

  • JUnit 测试可以自动运行并且检查自身结果并提供即时反馈。所以也没有必要人工梳理测试结果的报告。

  • JUnit 测试可以被组织为测试套件,包含测试用例,甚至其他的测试套件。

  • JUnit 在一个条中显示进度。如果运行良好则是绿色;如果运行失败,则变成红色。

  • JUnit测试减少后期维护时间以及成本

    导入JUnit4单元测试所需的jar包
    打开开发工具 eclipse|myeclipse -> 对应项目右击 > Build Path > Add Library > JUnit
    > 选择版本JUnit4 > Finish
    单元模块测试——单个类
    1、使用@Test注解
    例子:
    import static org.junit.Assert.assertEquals;
    import org.junit.Test;
    public class Test01
    {
    final static String CH = "中国";
    @Test
    //(命名格式建议用test+方法名)
    public void testCode()
    throws Exception
    {
    assertEquals("中国", CH);
    }

    }

    2、extend TestCase类
    例子:
    import junit.framework.TestCase;
    public class Test01 extends TestCase
    {
    final static String CH = "中国";
    //(命名格式建议用test+方法名) //继承TestCase,如命名方法没有test作为前缀则报错
    public void testCode()
    throws Exception
    {
    assertEquals("中国", CH);
    }

    }

    单元模块测试——多个类

    3、使用JUnitCore.runClasses(StudentTest01.class)返回Result类型;
       调用for (Failure failure : result.getFailures())进行遍历

    例子:
    import org.junit.runner.JUnitCore;
    import org.junit.runner.Result;
    import org.junit.runner.notification.Failure;
    public class TestRunner
    {

        public static void main(String[] args)
        {
            // TODO Auto-generated method stub
            Result result = JUnitCore.runClasses(StudentTest01.class);
            for (Failure failure : result.getFailures())
           
    {
                System.out.println(failure.toString());
            }
            // 测试过程中是否成功
            System.out.println(result.wasSuccessful());
        }
    }

    4、使用注解 @RunWith、@Suite.SuiteClasses

    例子:
    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    @RunWith(Suite.class)
    @Suite.SuiteClasses({
        //测试类作为参数,多个参数用逗号隔开
        StudentTest01.class, StudentTest02.class})
    public class AllTest
    {   }

    5、使用TestSuite类中的addTestSuite添加测试类、run(new TestResult())运行测试类

    例子:
    import junit.framework.TestResult;
    import junit.framework.TestSuite;
    public class AllTest
    {
        public static void main(String[] args)
        {
            TestSuite testSuite = new TestSuite();
            testSuite.addTestSuite(StudentTest01.class);
            testSuite.addTestSuite(StudentTest02.class);
            testSuite.run(new TestResult());

        }

    }


    参考链接:https://www.w3cschool.cn/junit/

转载于:https://my.oschina.net/u/3378039/blog/1843832

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值