`
ant04444
  • 浏览: 23033 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

JUnit - Tutorial

    博客分类:
  • java
 
阅读更多

original source :  http://www.vogella.com/articles/JUnit/article.html#junit_intro

 

JUnit - Tutorial

Lars Vogel

 

Version 2.1

 

02.04.2012

Revision History
Revision 0.1-0.5 03.09.2007 Lars
Vogel
JUnit description
Revision 0.6 - 2.1 10.05.2008 - 02.04.2012 Lars
Vogel
bugfixes and enhancements

Unit testing with JUnit

This tutorial explains unit testing with JUnit 4.x. It explains the creation of JUnit tests and how to run them in Eclipse or via own code.


This tutorial is part of this Kindle book:

 

Kindle Edition

1. Introduction

1.1. Unit Testing

A unit test is a piece of code written by a developer that executes a specific functionality in the code under test. Unit tests ensure that code is working as intended and validate that this is still the case after code changes.

1.2. Unit Testing with JUnit

JUnit 4.x is a test framework which uses annotations to identify methods that are tests. JUnit assumes that all test methods can be executed in an arbitrary order. Therefore tests should not depend on other tests.

To write a test with JUnit

  • Annotate a method with @org.junit.Test

  • Use a method provided by JUnit to check the expected result of the code execution versus the actual result

 

You can use Eclipse or the class "org.junit.runner.JUnitCore" to run the test.

2. Installation of JUnit

If you use Eclipse you can use the integrated JUnit in Eclipse for your testing.

If you want to control the used JUnit library explicitly, download JUnit4.x.jar from the JUnit website athttp://www.junit.org/ . The download contains the "junit-4.*.jar" which is the JUnit library. Add this library to your Java project and add it to the classpath.

3. Using JUnit

3.1. Preparation

Create a new project de.vogella.junit.first. We want to create the unit tests in a separate folder. The creation of a separate folder for tests is not mandatory. But it is a good practice to keep the code separated from the regular code. You might even create a separate project for the test classes, but we skip this step to make this example simpler.

Create a new source folder test via right-clicking on your project, select "Properties" and choose the "Java Build Path". Select the "Source" tab.

 

Create new source folder for the tests

 

Press "Add folder" then press "Create new folder". Create the folder "test".

 

Creating a new folder

 

Alternatively you can add a new source folder by right-clicking on a project and selecting New → Source Folder.

3.2. Create a Java class

In the "src" folder, create the de.vogella.junit.first package and the following class.

 

				
package de.vogella.junit.first;

public class MyClass {
	public int multiply(int x, int y) {
		return x / y;
	}
}
			

 

3.3. Create a JUnit test

Right click on your new class in the Package Explorer and select New → JUnit Test Case. Select "New JUnit 4 test" and set the source folder to "test", so that your test class gets created in this folder.

 

Create new test class

 

Press "Next" and select the methods which you want to test.

 

Selecting the methods to test

 

If the JUnit library in not part of your classpath, Eclipse will prompt you to do so.

 

Eclipes prompt for adding JUnit to the project class path

 

Create a test with the following code.

 

				
package de.vogella.junit.first;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyClassTest {

	@Test
	public void testMultiply() {
		MyClass tester = new MyClass();
		assertEquals("Result", 50, tester.multiply(10, 5));
	}
}
			

 

3.4. Run your test via Eclipse

Right click on your new test class and select Run-As → JUnit Test.

 

Run JUnit test via Eclipse

 

The result of the tests will be displayed in the JUnit View.

 

Result of running a unit test

 

The test should be failing (indicated via a red bar).

This is because our multiplier class is currently not working correctly (it does a division instead of multiplication). Fix the bug and re-run test to get a green bar.

If you have several tests you can combine them into a test suite. Running a test suite will execute all tests in that suite.

To create a test suite, select your test classes → right click on it → New → Other → JUnit → Test Suite.

 

Create a test suite

 

Select "Next" and select the methods for which you want to create a test.

Change the code to the following to make your test suite run your test. If you develop another test later you can add it to @Suite.SuiteClasses.

 

				
package mypackage;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses( { MyClassTest.class })
public class AllTests {
}

			

 

3.5. Run your test via code

You can also run your tests from via your own code. The class org.junit.runner.JUnitCore provides the method runClasses() which allows you to run one or several tests classes. As a return parameter you receive an object of the type org.junit.runner.Result. This object can be used to retrieve information about the tests.

In your "test" folder create a new class MyTestRunner with the following code. This class will execute your test class and write potential failures to the console.

 

				
package de.vogella.junit.first;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class MyTestRunner {
	public static void main(String[] args) {
		Result result = JUnitCore.runClasses(MyClassTest.class);
		for (Failure failure : result.getFailures()) {
			System.out.println(failure.toString());
		}
	}
}

			

 

4. JUnit (more) in Detail

4.1. Static imports with Eclipse

JUnit uses a lot of static methods and Eclipse cannot always correctly automatically import static imports.

You can make the JUnit test methods available via the content assists.

Open the Preferences via Window -> Preferences and select Java → Editor → Content Assist → Favorites.

Use the new "New Member" button to add the methods you need. The example below makes the assertTrue,assertFalse and assertEquals methods available.

 

Adding static imports to the preferences

 

You can now use Content Assist (Ctrl+Space) to add the method and the import.

I suggest to add at least the following new members:

  • org.junit.Assert.assertTrue

  • org.junit.Assert.assertFalse

  • org.junit.Assert.assertEquals

  • org.junit.Assert.fail

 

4.2. Annotations

The following table gives an overview of the available annotations in JUnit 4.x.

 

Table 1. Annotations

Annotation Description
@Test public void method() The annotation @Test identifies that a method is a test method.
@Before public void method() Will execute the method before each test. This method can prepare the test environment (e.g. read input data, initialize the class).
@After public void method() Will execute the method after each test. This method can cleanup the test environment (e.g. delete temporary data, restore defaults).
@BeforeClass public void method() Will execute the method once, before the start of all tests. This can be used to perform time intensive activities, for example to connect to a database.
@AfterClass public void method() Will execute the method once, after all tests have finished. This can be used to perform clean-up activities, for example to disconnect from a database.
@Ignore Will ignore the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
@Test (expected = Exception.class) Fails, if the method does not throw the named exception.
@Test(timeout=100) Fails, if the method takes longer than 100 milliseconds.


4.3. Assert statements

The following table gives an overview of the available assert statements.

 

Table 2. Test methods

Statement Description
fail(String) Let the method fail. Might be used to check that a certain part of the code is not reached. Or to have failing test before the test code is implemented.
assertTrue(true) / assertTrue(false) Will always be true / false. Can be used to predefine a test result, if the test is not yet implemented.
assertTrue([message], boolean condition) Checks that the boolean condition is true.
assertsEquals([String message], expected, actual) Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays.
assertsEquals([String message], expected, actual, tolerance) Test that float or double values match. The tolerance is the number of decimals which must be the same.
assertNull([message], object) Checks that the object is null.
assertNotNull([message], object) Checks that the object is not null.
assertSame([String], expected, actual) Checks that both variables refer to the same object.
assertNotSame([String], expected, actual) Checks that both variables refer to different objects.


5. Mocking with EasyMock

Unit testing uses also mocking of objects. In this case the real object is replaced by a replacement which has a predefined behavior the test. There are several frameworks available for mocking. To learn more about mock frameworks please see EasyMock Tutorial

6. Thank you

 

 

Please help me to support this article:

Flattr this  

 

7. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

分享到:
评论

相关推荐

    JUnit-Tutorial.zip_JUnit_zip

    这个“JUnit Tutorial.zip”压缩包包含了一份详细的JUnit实战教程PDF,旨在帮助初学者和经验丰富的开发者更好地理解和运用JUnit进行软件质量保证。 一、JUnit简介 JUnit是一个开源项目,最初由Ernst Meyer和Kent ...

    fullstack-tutorial

    "fullstack-tutorial-master" 文件可能是项目主分支的源代码,包含了上述所有技术的示例和教程。通过这个项目,你可以学习到如何从零开始搭建一个全功能的Web应用,同时熟悉开发流程和最佳实践。无论是个人学习还是...

    IntelliJ-IDEA-Tutorial-newMaster

    2. 单元测试:支持JUnit和TestNG等测试框架,编写和运行测试用例,确保代码质量。 七、插件扩展 1. 插件市场:在“Preferences”>“Plugins”中,可以浏览和安装各种插件,增强IDE功能,如Lombok、GitFlow、Code...

    IntelliJ-IDEA-Tutorial, IntelliJ IDEA 简体中文专题教程.zip

    5. **调试与测试**:教授如何设置断点、单步执行、查看变量值、进行远程调试,以及使用JUnit等框架进行单元测试和集成测试。 6. **运行与部署**:讲解如何配置运行/调试配置,运行应用程序,以及部署到服务器,如...

    Android代码-android-unit-testing-tutorial

    Android单元测试(三):JUnit单元测试框架的使用 代码和测试代码在junit子package下面 Android单元测试在蘑菇街支付金融部门的实践 代码和测试代码在groupshare子package下面 Android单元测试(四):Mock以及Mockito...

    automation-testing-with-java-and-selenium:学习使用Java和Selenium进行自动化测试

    JUnit- https://courses.in28minutes.com/p/junit-tutorial-for-beginners Mockito- https: //courses.in28minutes.com/p/mockito-for-beginner-in-5-steps 安装工具 安装视频: https : //www.youtube.co

    roman10-android-tutorial

    在"roman10-android-tutorial-master"中,我们可以期待看到以下的知识点: 1. **环境配置**:包括安装Android Studio,这是官方推荐的集成开发环境(IDE),以及配置Android SDK,这包含了一系列用于构建、调试和...

    JUNG2-Tutorial

    ### JUNG2-Tutorial:Java Universal Network/Graph框架详解 #### 一、引言与概述 JUNG2(Java Universal Network/Graph Framework)是JUNG(Java Universal Network/Graph)框架的一个重大修订版本,旨在为Java...

    JUnit Testing Utility Tutorial.pdf

    ### JUnit 测试工具教程详解 #### 一、引言 JUnit 是一个为 Java 编程语言设计的单元测试框架。它提供了一种简单而有效的方法来显式地测试 Java 程序中的特定部分。JUnit 的核心优势在于其可扩展性以及能够单独或...

    appfuse-tutorial-struts-1.6.zip_appfuse

    这个"appfuse-tutorial-struts-1.6.zip"文件是一个基于Struts 1.6的AppFuse教程,用于指导开发者如何构建一个企业级的人员管理系统。Struts是Apache软件基金会下的一个开源框架,专门用于构建基于MVC(Model-View-...

    ICEFaces :autocomplete-tutorial.zip

    这个"autocomplete-tutorial.zip"压缩包提供了一个关于如何在ICEFaces框架中使用自动补全功能的教程。自动补全功能是用户界面中常见的一种特性,允许用户在输入时获得建议或匹配项,通常用于搜索框或者表单字段,...

    travis-ci-tutorial-java:只是为了学习如何在Java项目中使用travis-ci!

    travis-ci-tutorial-java 只是为了学习如何在Java项目中使用travis-ci! 这是一个如何在GitHub上将Travis CI(和Codecov)与Java结合使用的最小工作示例。 它使用测试框架如何开始此存储库转到并启用存储库修复...

    j2ee-1_4-doc-tutorial

    - 使用 JUnit 进行单元测试和集成测试。 通过这个 J2EE 1.4 教程,开发者可以深入理解 J2EE 平台的核心组件和工作原理,从而能够构建健壮、可扩展的企业级应用。同时,教程还涵盖了安全、性能优化和故障排查等方面...

    JMeter-Tutorial.pdf

    - **创建 JUnit 请求**: 添加 JUnit 请求采样器。 - **编写测试代码**: 在采样器中编写 Java 代码实现测试逻辑。 - **配置监听器**: 添加监听器显示测试结果。 - **执行测试**: 运行测试计划。 #### 十三、录制 ...

    Java-Reflection-Tutorial.pdf

    - 测试工具:JUnit测试框架使用反射来调用私有方法或构造器。 - 日志和监控:监控系统性能,记录运行时信息。 3. **类与接口** - 类:反射允许创建未知类型的对象,调用其方法,访问字段,甚至改变其内部状态。 ...

    spring-boot-rest-api-tutorial-master.rar

    Spring Boot REST API Tutorial Master 是一个基于Spring Boot框架的示例项目,它展示了如何构建RESTful Web服务。这个项目是为那些想要学习如何在Spring Boot环境中创建高效、可伸缩的API的人准备的。REST...

    Maven-Tutorial.md

    <artifactId>junit <version>4.13.1 <scope>test ``` 3. **保存文件**:保存 `pom.xml` 文件后,Maven 会自动下载并添加依赖到项目中。 #### 5. 常见问题 ##### 依赖下载失败 1. **检查网络连接**:确保...

    spring-rest-bookmarks-tutorial:在 http 上找到的教程

    在文件名"spring-rest-bookmarks-tutorial-master"中,我们可以推断这是教程项目的源代码仓库,"master"分支可能包含了完整的示例应用。通过查看源代码,可以学习到上述知识点的实际应用,例如如何定义Controller,...

    async-servlet-tutorial

    在“async-servlet-tutorial-master”这个文件夹中,可能包含了以下内容: 1. **源代码**:包括Servlet的Java源文件,可能有一个或多个异步Servlet的实现。 2. **配置文件**:如web.xml,用于配置Servlet和监听器,...

Global site tag (gtag.js) - Google Analytics