original source : http://www.vogella.com/articles/JUnit/article.html#junit_intro
JUnit - Tutorial
Lars Vogel
Version 2.1
Copyright © 2007, 2008, 2009, 2010, 2011, 2012 Lars Vogel
02.04.2012
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 |
Table of Contents
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.
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.
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.
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.
Press "Add folder" then press "Create new folder". Create the folder "test".
Alternatively you can add a new source folder by right-clicking on a project and selecting New → Source Folder.
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; } }
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.
Press "Next" and select the methods which you want to test.
If the JUnit library in not part of your classpath, Eclipse will prompt you to do so.
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)); } }
Right click on your new test class and select Run-As → JUnit Test.
The result of the tests will be displayed in the JUnit View
.
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.
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 { }
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()); } } }
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.
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
The following table gives an overview of the available annotations in JUnit 4.x.
Table 1. Annotations
@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. |
The following table gives an overview of the available assert statements.
Table 2. Test methods
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. |
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
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 e-book
Android单元测试(三):JUnit单元测试框架的使用 代码和测试代码在junit子package下面 Android单元测试在蘑菇街支付金融部门的实践 代码和测试代码在groupshare子package下面 Android单元测试(四):Mock以及Mockito...
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
travis-ci-tutorial-java 只是为了学习如何在Java项目中使用travis-ci! 这是一个如何在GitHub上将Travis CI(和Codecov)与Java结合使用的最小工作示例。 它使用测试框架如何开始此存储库转到并启用存储库修复...
JUnit is a framework for implementing testing in Java. It provides a simple way to explicitly test specific areas of a Java program, it is extensible and can be employed to test a hierarchy of program...
Cucumber教程先决条件: 在Eclipse中为功能文件安装Natural 依存关系< dependencies><...-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->< dependency>< groupId>info.cukes</ group
1. JUnit 5开发人员指南 2. GitHub存储库 3.重要的Java开发人员指南 Spring开发人员指南 Maven开发人员指南 4. JUnit 4与JUnit 5的备忘单 5.下载PDF版的《 JUnit 5用户指南》。 ...
样本AEM项目模板 这是基于AEM的应用程序的项目模板。... ui.launcher:包含粘合代码,该粘合代码将ui.tests捆绑包(和相关捆绑包)部署到服务器并触发远程JUnit执行 ui.frontend:可选的专用前端构建机制(Angula
The tutorial gives a profound entry point in the essentials of unit testing with JUnit and prepares you for test-related daily work challenges. Style and approach This is an intelligible tutorial ...
是Java语言开发的集成环境,IDEA在发展中国家被公认为最好的Java开发工具之一,尤其是在智能代码助手,代码自动提示,重构,J2EE支持,各种版本工具(Git,SVN,GitHub等),JUnit,CVS集成,代码分析和创新的GUI...
本教程以使用junit测试用例针对不同功能的示例为例,说明了 Java api的用法。第1部分介绍ElasticSearch集群设置以及ES入门。 索引,文档类型,节点,分片/副本, 创建/检索/更新/删除文档模式映射,字段,过滤器,...
本指南将引导您完成创建Spring应用程序,然后使用JUnit对其进行测试的过程。 你会建立什么 您将构建一个简单的Spring应用程序,并使用JUnit对其进行测试。 您可能已经知道如何编写和运行应用程序中各个类的单元测试...
JUnit- 安装工具 PDF: : 概述 介绍 我们喜欢编程。 本课程的目的是为了热爱编程。 Java是最流行的编程语言之一。 Java提供了面向对象和功能编程的功能。 我们采用结合JShell(Java 9中的一个很棒的新功能)和...
tested as an example, and the resultant tutorial therefore took five times longer to digest than it should have. There is no need to learn to understand somebody else's data structures just to learn ...
Testing with JUnit4 Testing with Espresso Testing with UI Automator Measuring Test Coverage Unit Testing MonkeyRunner and the Test Monkey Java 8 Lambda Expressions Rx Basics Notifications Advanced ...
A step-by step-tutorial with illustrative examples that will let you master using Xtext and implementing DSLs with its custom language, Xtend. Table of Contents Chapter 1: Implementing a DSL Chapter ...
25 Testing Classes Using JUnit 26 JNI (example provided by Leslie Sears) 27 The StringTokenizer Class Part IV -- Database Supplements 1 SQL statements for creating and initializing tables used ...
Testing with JUnit4 Testing with UI Automator Measuring Test Coverage Unit Testing MonkeyRunner and the Test Monkey Notifications Advanced Notifications Introducing GridLayout The Percent Support ...
通过将 tutorialj 与 JUnit 注释相结合,还可以轻松检查使用示例是否也按预期运行。 我们不试图具有互操作性或取代 javadoc。 我们希望用这个工具注释的方法与用 javadoc 注释的方法是不相交的:javadoc 以公共 ...