`

JUnit Cookbook - Junit菜单

阅读更多

J U nit Cookbook

Kent Beck, Erich Gamma



Here is a short cookbook showing you the steps you can follow in writing and organizing your own tests using JUnit.

这是一个简短的说明,你可以跟随用JUnit书写和组织你自己的测试

Simple Test Case

简单的测试用例

How do you write testing code?

如何编写测试代码?

最简单的方法是作为一个表达式在debugger中。你可以不用重新编译的去改变调试表达式,并且你能等待去决定直到你看到运行对象使书写

The simplest way is as an expression in a debugger. You can change debug expressions without recompiling, and you can wait to decide what to write until you have seen the running objects. You can also write test expressions as statements which print to the standard output stream. Both styles of tests are limited because they require human judgment to analyze their results. Also, they don't compose nicely- you can only execute one debug expression at a time and a program with too many print statements causes the dreaded "Scroll Blindness".

JUnit tests do not require human judgment to interpret, and it is easy to run many of them at the same time. When you need to test something, here is what you do:

  1. Annotate a method with @org.junit.Test用@org.junit.Test来注视一个方法
  2. When you want to check a value, import org.junit.Assert.* statically, call assertTrue () and pass a boolean that is true if the test succeeds当你想要检验一个值,导入静态的org.junit.Assert.*,调用assertTure()方法并且如果测试成功会传递一个为真的布尔值

For example, to test that the sum of two Moneys with the same currency contains a value which is the sum of the values of the two Moneys, write:例如,测试

@Test public void simpleAdd() {
    Money m12CHF= new Money(12, "CHF"); 
    Money m14CHF= new Money(14, "CHF"); 
    Money expected= new Money(26, "CHF"); 
    Money result= m12CHF.add(m14CHF); 
    assertTrue(expected.equals(result));
}

If you want to write a test similar to one you have already written, write a Fixture instead.

如果你想要写一个类似于您已经写好的测试时,写一个Fixture代替。

Fixture

What if you have two or more tests that operate on the same or similar sets of objects?

如果你有两个或更多的测试去作用在相同或相似的一类对象。

测试需要

Tests need to run against the background of a known set of objects. This set of objects is called a test fixture. When you are writing tests you will often find that you spend more time writing the code to set up the fixture than you do in actually testing values.

To some extent, you can make writing the fixture code easier by paying careful attention to the constructors you write. However, a much bigger savings comes from sharing fixture code. Often, you will be able to use the same fixture for several different tests. Each case will send slightly different messages or parameters to the fixture and will check for different results.

When you have a common fixture, here is what you do:

  1. Add a field for each part of the fixture在fixture的每一个部分添加一个属性
  2. Annotate a method with @org.junit.Before and initialize the variables in that method用@org.junit.Before注释一个方法并在这个方法中初始化变量
  3. Annotate a method with @org.junit.After to release any permanent resources you allocated in setUp用@org.junit.After注释一个方法去释放任何分到到setUp方法中的永久性资源

For example, to write several test cases that want to work with different combinations of 12 Swiss Francs, 14 Swiss Francs, and 28 US Dollars, first create a fixture:

例如,写一些测试用例去和不同的合作12法国货币,14法国国币,和28美元,首先建立一个fixture:

public class MoneyTest { 
    private Money f12CHF; 
    private Money f14CHF; 
    private Money f28USD; 
    
    @Before public void setUp() { 
        f12CHF= new Money(12, "CHF"); 
        f14CHF= new Money(14, "CHF"); 
        f28USD= new Money(28, "USD"); 
    }
}

Once you have the Fixture in place, you can write as many Test Cases as you'd like. Add as many test methods (annotated with @Test) as you'd like.

一旦有了Fixture,你能写一些你喜欢的测试用例。加一些你喜欢测试方法(用@Test注释)

Running Tests

运行测试

How do you run your tests and collect their results?

怎么运行你的测试并关联这些结果?

Once you have tests, you'll want to run them. JUnit provides tools to define the suite to be run and to display its results. To run tests and see the results on the console, run this from a Java program:

一旦你拥有了测试,你将要去运行他们。junit提供一套运行和显示结果的工具。运行测试并且在控制台看到结果,在一个Java项目中运行它:

org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);

or this from the command line, with both your test class and junit on the classpath:

或者从下面的命令,将你的测试类和junit放在你的classpath环境变量中:

java org.junit.runner.JUnitCore TestClass1.class [...other test classes...]

You make your JUnit 4 test classes accessible to a TestRunner designed to work with earlier versions of JUnit, declare a static method suite that returns a test.

你制作你的Junit4测试类访问一个TestRunner设计去工作早期的junit版本,描述一个返回一个测试的静态的方法suite

public static junit.framework.Test suite() { 
    return new JUnit4TestAdapter(Example.class); 
}

Expected Exceptions

How do you verify that code throws exceptions as expected?

Verifying that code completes normally is only part of programming. Making sure the code behaves as expected in exceptional situations is part of the craft of programming too. For example:

怎么去检验代码抛出期望的异常。

检验的代码通常仅仅是程序中的一部分。确信代码

new ArrayList<Object>().get(0); 


This code should throw an IndexOutOfBoundsException. The @Test annotation has an optional parameter "expected" that takes as values subclasses of Throwable. If we wanted to verify that ArrayList throws the correct exception, we would write:

@Test(expected= IndexOutOfBoundsException.class) public void empty() { 
    new ArrayList<Object>().get(0); 
}

分享到:
评论

相关推荐

    Mockito Cookbook - Packt

    ### Mockito Cookbook - 关键知识点概览 #### 一、Mockito框架简介 - **定义**:Mockito是一款Java测试框架,用于轻松创建被测系统的协作者(即与被测对象交互的对象)的模拟对象(mocks)。通过这些模拟对象可以更...

    java-cookbook-problems-solutions-developers-4th.rar

    11. **测试与调试**:介绍如何使用JUnit进行单元测试,以及调试技巧,确保代码的质量和可靠性。 12. **性能优化**:提供了关于内存管理、垃圾收集、代码性能分析和调优的指导,帮助开发者写出高效的应用程序。 ...

    Java Cookbook - Problems and Solutions for Java Developers

    12. **测试与调试**:涵盖了单元测试、集成测试的方法,如JUnit和Mockito,以及如何使用Java的调试工具进行问题定位。 此外,书中的每个问题都配以详细的代码示例,便于读者理解和实践。作者还强调,尽管书中的信息...

    Cookbook-android:适用于 android 的示例食谱

    综上所述,《Cookbook-android》项目覆盖了Android开发的多个核心方面,通过实际的示例代码,开发者可以学习到如何有效地利用Android SDK进行应用开发。这个项目不仅适合初学者入门,也对经验丰富的开发者具有参考...

    JavaExtremeProgrammingCookbook.pdf

    ### Java Extreme Programming Cookbook 关键知识点概述 #### 一、书籍概览 - **书名**:《Java Extreme Programming Cookbook》 - **作者**:Eric M. Burke 和 Brian M. Coyner - **出版社**:O’Reilly & ...

    CookBook-Robotium:使用 Robotium 测试 Android 应用程序

    由于 Robotium 是基于JUnit4构建的,所以确保你的测试类也继承自 JUnit4 的 `TestCase` 类。在你的 app 的 build.gradle 文件中添加如下依赖: ```groovy androidTestImplementation '...

    Junit Recipes 源码

    7. **JUnit Cookbook Examples**: "Cookbook"通常指的是提供解决方案的集合,这部分源码可能是JUnit测试的实用示例集合,涵盖各种测试策略和技术。 8. **CoffeeShopJdbc**: Jdbc(Java Database Connectivity)是...

    Spring Boot 2 Cookbook 第二版

    本书将讲解如何进行单元测试、集成测试以及端到端测试,包括使用JUnit、Mockito和Spring Boot测试工具。 除此之外,Spring Boot 2还加强了对云平台的支持,如Heroku、Docker和Kubernetes。书中会介绍如何打包Spring...

    Android cookbook example

    14. **单元测试与集成测试**:使用JUnit、Espresso或Robolectric进行应用的测试,确保代码质量。 15. **Gradle构建系统**:了解如何配置build.gradle文件,使用依赖管理和构建变体。 16. **Android插件化**:如果...

    Mockito Cookbook

    《Mockito Cookbook》是一本专注于Java单元测试的实用指南,特别强调了Mockito框架的使用。Mockito是一款广泛应用于Java开发中的测试驱动开发(TDD)工具,它允许开发者创建和配置模拟对象,以便在测试中隔离代码并...

    RESTful Web Services Cookbook

    - 自动化测试框架如JUnit、PyTest。 10. **性能优化** - 响应式设计,减少响应时间。 - 缓存策略,如ETag和If-Modified-Since头。 - 资源聚合,减少网络请求次数。 综上所述,《RESTful Web Services Cookbook...

    eclipse cookbook code

    8. **测试与性能优化**:"ch12"可能涵盖JUnit测试框架的使用,以及Eclipse内置的性能分析工具,帮助开发者编写高质量的代码并优化程序性能。 9. **团队协作与持续集成**:"ch13"可能讲解如何在Eclipse中集成版本...

    Spring MVC Cookbook(PACKT,2016).pdf

    《Spring MVC Cookbook》是由PACKT Publishing在2016年出版的一本专著,主要针对Spring MVC框架提供了实用的解决方案和技巧。Spring MVC是Spring框架的一部分,它为构建基于Java的Web应用程序提供了一个模型-视图-...

    jmock cookbook 资源整合

    6. **与JUnit和其他测试框架集成**:JMock可以无缝集成到JUnit、TestNG等流行的测试框架中,使得测试代码更加简洁和整洁。 7. **面向切面编程(AOP)**:JMock基于Java代理和动态代理实现,这使得它具备面向切面编程...

    Android+Cookbook实用开发技巧集101.pdf

    书中会介绍JUnit、Espresso和Mockito等测试框架的使用,以及如何进行远程调试和Monkey测试。 10. **Gradle构建系统**:Gradle是Android的主要构建工具,书中会讲解Gradle的基本用法,构建脚本的编写,依赖管理和多...

Global site tag (gtag.js) - Google Analytics