JUnit Unit Test Tutorial-The ultimate guide
- The ultimate guide to JUnit Unit Testing tutorials
- Description
- Introduction to Unit Testing
- 1 What is unit testing
- 2 Test coverage
- 3 unit tests in Java
- About JUnit
- 1 using Eclipse to implement a simple JUnit test example
- Implementing the complete JUnit example with eclipse
- 1 Creating a Project
- 2 Creating a Java class to be tested
- 3 Creating and running JUnit test Cases
- 4 using Ignore annotations
- 5 Creating a test suite suite tests
- 6 Creating a parameterized test parameterized tests
- 7 Rule Rules
- 8 Strategy Categories
- Command line run JUnit test
Description
This tutorial is translated from Java Code Geeks, the original URL: https://www.javacodegeeks.com/2014/11/junit-tutorial-unit-testing.html#suite_tests. In the process of translation, a small part of the content is the translator added explanation and the original article in the wrong place correction. The level is limited, if has the wrong place, hoped can in my blog to tell me, thanks.
Related examples do not want to write their own classmates can go here download: http://download.csdn.net/detail/rainnnbow/9603847
1. Introduction to Unit Testing 1.1 what is a unit test?
A unit can be a method, a class, a package, or a subsystem. So the term unit test represents the test behavior of very small units in the code to ensure that they work as expected. For example, let's give some input, test if it's the expected output, or test whether a condition is true or false.
This kind of test behavior can help developers find bugs hidden behind the code and improve the quality of their code. Unit tests are also used to ensure that the code works as expected to prevent possible future changes.
1.2 Test coverage
Overall, the developer community has a different view of how much code testing needs to be achieved. Many developers believe that the code should have a test coverage of up to 100%. Others think 50% or more must not is possible. But in any case, you should write tests for the complex and important parts of your code.
1.3 Unit Tests in Java
The most famous test framework in Java is JUnit, and this guide is dedicated to JUnit, and the next section details more about the test framework. Another well-known test framework in Java is testng.
2. Introduction to JUnit
JUnit is an open-source test framework that is used to write and run repeatable automated tests to ensure that our code executes as expected. JUnit is widely used: it can be used alone in Java programs (using the command line) or in conjunction with the IDE, such as Eclipse.
JUnit provides the following features:
- Asserts the expected result of the test.
- The characteristics of the shared test data.
- Use test suites to simplify the organization and operation of your testing cases.
- Graphical and textual test cases? (Graphical and textual test runners.)
JUnit can be used to test the following:
- An object
- Part of an object--a method or several interacting methods
- Interaction between multiple objects
2.1 Using Eclipse to implement a simple JUnit test example
In this section we will show a simple junit example. First look at the classes we want to test:
Calculate.java:
package com.javacodegeeks.junit;
public class Calculate {
public int sum(int var1, int var2) {
System.out.println("Adding values: " + var1 + " + " + var2);
return var1 + var2;
}
}
In the above source code, we see that the class has a public method sum (), the method accepts two int parameters, and then returns the result after the addition. We will test this method. So we need to create another class and write a test method in this class for all the test method one by one in the test calculate class (in this case, we only have one method to test). This is the most common way to use it. Of course, if a method is very complex, we can write multiple test methods for this method. Write more details about the test case, which we'll cover in the next section. The following Calculatetest.java class is our test class:
package com.javacodegeeks.junit;
import static org.junit.Assert.*;
import org.junit.Test;
public class CalculateTest {
Calculate calculation = new Calculate();
int sum = calculation.sum(2, 5);
int testSum = 7;
@Test
public void testSum() {
System.out.println("@Test sum(): " + sum + " = " + testSum);
assertEquals(sum, testSum);
}
}
Let's try to explain the code above. First we see a @test annotation on the Testsum () method. This annotation indicates that this method can be run as a test case. So the Testsum () method is used to test the sum () method. We also see the assertequals (Sum, testsum) method, Assertequals ([String message], object expected, object Actual) method used to take over two objects, and asserts whether the two objects are equal.
Running the test class, run As–>junit test, the program output will resemble the following:
In order to see the actual results of the JUnit tests, Eclipse provides a junit window to display the test results. In this case, the test succeeds and the JUnit window does not display any error or failure information, so we see the interface as shown below:
If we change the code:
int testSum = 10;
After modifying the code, the tests for the two integers are no longer equal, and the program output looks like this:
Also, a test error is displayed in the JUnit window and an error message is given:
2.2 JUnit Annotations
In this section we will cover basic annotations for JUNIT4 support, and the following table is a summary of these indexes:
Let's take a look at an example of a test class that contains the above annotations:
Annotationstest.java:
package com.javacodegeeks.junit;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class AnnotationsTest {
private ArrayList testList;
/**
* if the method isn‘t static, throw following exception:
* java.lang.Exception: Method onceExecutedBeforeAll() should be static
*/
@BeforeClass
public static void onceExecutedBeforeAll() {
System.out.println("@BeforeClass: onceExecutedBeforeAll");
}
@Before
public void executedBeforeEach() {
testList = new ArrayList();
System.out.println("@Before: executedBeforeEach");
}
/**
* If the method isn‘t static, throw following exception:
* java.lang.Exception: Method onceExecutedAfterAll() should be static
*/
@AfterClass
public static void onceExecutedAfterAll() {
System.out.println("@AfterClass: onceExecutedAfterAll");
}
@After
public void executedAfterEach() {
testList.clear();
System.out.println("@After: executedAfterEach");
}
@Test
public void EmptyCollection() {
assertTrue(testList.isEmpty());
System.out.println("@Test: EmptyArrayList");
}
@Test
public void OneItemCollection() {
testList.add("oneItem");
assertEquals(1, testList.size());
System.out.println("@Test: OneItemArrayList");
}
@Ignore
public void executionIgnored() {
System.out.println("@Ignore: This execution is ignored");
}
}
To perform the above test, the console output looks like this:
The JUnit window displays the following information:
2.3 JUnit Assertion
In this section we will show some assertion methods. All of these methods are provided by the Assert class, and the Assert class inherits from Java.lang.Object. These assertions can help you write test cases and monitor failed tests. The following table is a detailed description of some of the most common assertion methods:
Let's look at an example of the above assertion:
Assertionstest.java
package com.javacodegeeks.junit;
import static org.junit.Assert.*;
import org.junit.Test;
public class AssertionsTest {
@Test
public void test() {
String obj1 = "junit";
String obj2 = "junit";
String obj3 = "test";
String obj4 = "test";
String obj5 = null;
int var1 = 1;
int var2 = 2;
int[] arithmetic1 = {1,2,3};
int[] arithmetic2 = {1,2,3};
assertEquals(obj1, obj2);
assertSame(obj3, obj4);
assertNotSame(obj2, obj4);
assertNotNull(obj1);
assertNull(obj5);
assertTrue(var1 != var2);
assertFalse(var1 == var2);
assertArrayEquals(arithmetic1, arithmetic2);
}
}
From the above class we can see how the assertion method works.
- Assertequals (): If two objects are equal, the method returns normally, otherwise an error is displayed in the JUnit window and the test is interrupted.
- Assertsame () and Assertnotsame (): Tests whether a reference to a two object points to the same object.
- Assertnull () and Assertnotnull (): Tests whether a variable is null or non-null.
- Asserttrue () and Assertfalse (): TRUE or false when testing a condition or variable.
- Assertarrayequals (): Compares two arrays for equality. If it is equal, the method returns normally, otherwise an error will be displayed in the JUnit window and the test is interrupted.
3. Implementing the complete JUnit example with eclipse
In this section we will show a complete example of using JUnit. We'll explain how to create and run test cases, and how to use junit annotations and assertions.
3.1 Creating a Project
Create a Java project named Junitguide. Create a package com.javacodegeeks.junit used to put the class that is being tested. A good practice for test classes is to create a source package that is dedicated to testing. In this way, the test class and the test class are divided into different source packages. Create Test Package: Right-click your project, New–>source Folder, name the source package as test.
Tip: Another way to create a source package: Right-click your project? Properties? Java Build Path, select the source entry, and then add Folder? Create New Folder. Enter the source package name and click Finish.
You can see that there are two source packages in the project:
You can also create a package called Com.javacodegeeks.junit in the test source package so that your test class will not be placed in the default package.
3.2 Creating a Java class to be tested
Right-click the SRC source package and create a class named Firstdayatscholl.java. The public method of the class will be tested.
Firstdayatschool.java
3.3 Creating and running JUnit test Cases
Create a test case for a class Firstdayatschool.java that already exists: Select the Firstdayatschool.java class, right-click to select New? JUnit Test case. Change the source package and put the test case class in the testing source package. Make sure that the JUnit 4 test option is selected.
Click "Finish". If your project does not contain JUNIT4 under Classpath, the information shown below will pop up to allow you to add the JUNIT4 library into your project.
(Translator Note: You can also create a test case class directly in the test source package just as you would create a normal class.) As long as the methods in this class are annotated with @test annotations, you can introduce the JUnit framework and become a test case. )
Here is the test case that we created named Firstdayatschooltest.java.
Firstdayatschooltest.java
Right-click Run as? JUnit test, run the test case.
The program output is as follows:
The JUnit window appears as follows:
The JUnit window does not have any errors or failures at this time. If we change one of the arrays, let it contain more elements than expected:
Run the test class again, and the JUnit window will display a failed test case:
Or, let's change the array again to include the elements that are different from the expected:
Run the test class again, and the JUnit window will again display a test case, fail:
3.4 Using @ignore annotations
In the example above, let's look at how to use @ignore annotations. @ignore annotations are annotated on the Testaddpencils () method of the test class Firstdayatschooltest.java. In this way, we ignore the test method and do not perform the test.
To perform the test, the output is as follows: The test method for the @Ignore annotation is not executed.
The JUnit window appears as follows:
Now, we remove the @ignore annotation on the Testaddpencils () method and label the @ignore annotation on the Firstdayatschooltest.java class.
Run the Test class discovery: The entire test case will not be executed, so there is no output on the console. The JUnit window displays the following information:
3.5 Creating a test suite (suite tests)
In this section, we'll show you how to create a test suite. A test suite is a collection of multiple test cases from different classes. Use @runwith and @suite annotations to allow these test classes to run together. This is useful when you have many test classes and you want these test classes to be executed together.
On the basis of the previous section class, we can create two test classes. One Test Preparemybag () method, another test Addpencils () method. The two test classes are as follows:
Preparemybagtest.java.
Addpencilstest.java.
Let's create a test suite class to run the above two test classes. The test suite class Suitetest.java looks like this:
Suitetest.java.
Use @suite.suiteclasses annotations to define which test classes will be included in the test suite to be executed together.
Run the test suite, and the two test classes will be executed in the order declared in the @suite.suiteclasses annotations.
After execution, the JUnit window displays the following information:
3.6 Creating a parametric test (parameterized tests)
In this section we will show how to create a parameterized test. We will use the class in the previous 2.1 section as the class being tested.
When does a test class be considered a parameterized test class? When the test class meets the following conditions:
? This class uses @runwith (Parameterized.class) notation;
Instead of using the JUnit built-in default executor, @RunWith note tells JUnit to execute the test case using the executor indicated by the note. Parameterized is an executor in JUnit that executes an identical test case multiple times using a different set of inputs.
? The class has a unique constructor to create the test data;
? The class has a static method used to produce and return the test data, which uses the @parameters annotation callout;
? The class has a test case labeled with @test (Translator Note: This is not a nonsense).
We have created a new test class Calculatetest.java. This class follows the rules above. This type of source code is as follows:
Above, as the code satisfies all the rules above. The Addednumbers method uses the @parameters callout to return the collection of arrays. Each array contains the I/O data for the test execution. The number of elements in the array must be the same as the number of arguments in the constructor. In this example, an array contains three elements, two represent the number to be added, and one represents the result.
Run the test case, and the console output looks like this:
The JUnit window output information is as follows:
As you can see from the above information, the test case was executed 4 times, which is the number of test data entered in the method using the @parameters annotation callout.
3.7 Rule (rules)
In this section we will introduce a new feature of JUNIT4 called Rules. Rules allow us to flexibly add or redefine the behavior of each test method. To achieve this, use the @rule annotation to label the fields of public in the Test class. These fields must be of type methodrule, and they indicate what changes have been made to the run of a test method or the result report. A test method can apply multiple methodrule. The Methodrule interface has many implementations, such as Errorcollector, which allow the test case to continue running when the first error is found, ExpectedException, which allows us to specify the type and exception information of the expected exception; TestName, This rule allows us to get the name of the current test method in the test method, and so on other rules. In addition to the rules that JUnit has already defined, developers can customize the rules and use them in test cases.
Below, we show an example of using a testname rule that already exists. TestName is called when a test class starts executing.
Nameruletest.java
As shown above: The @Rule annotation labels a public domain name, which is of type Methodrule. Specifically, the class is the implementation class Methodrule type of the Methodrule interface. We can then use name to get the name of the currently running test method in our test method.
(Translator Note: For a detailed description of the Rules, please see JUNIT4 official documentation: Https://github.com/junit-team/junit4/wiki/Rules. Run inside the example, have questions on the modified example test, at a glance. Rules are still a lot of use. )
3.8 Strategy (Categories)
Another new feature of JUnit is policy, which allows you to put specific tests together to form a grouping (group) and can include or exclude certain groupings. For example, you can separate a test case that is running slowly from a test case that runs fast. JUnit provides a @category annotation that identifies a policy for a test case. The following is an example of using this new feature. This feature is supported starting from JUnit4.8.
First, define two policies, fasttests and slowtests. A strategy can be a class or an excuse.
In the above code, we use the @category annotation on the B () method of Class A, labeling the method in the Slowtests strategy. Therefore, @Category annotations can not only label the entire class, but also label a test method.
In the above code, we see that the whole class B uses the @category callout. After labeling on a class, all test methods for that class are automatically included in the policy declared in @category. We can also see that a class or a test method can belong to more than one policy.
In the above code, we see a test suite named Slowtestsuite_1. In general, we think of a strategy as a test suite. In this suite, we use @includecategory annotations to indicate which policies will be executed. In this example, all methods that belong to the slowtests policy will be executed. Therefore, the B () method in Class A and the C method in class B are executed, and they all belong to the slowtests policy.
In the above code, we have made some modifications to the test suite, and we have added a new annotation @excludecategory, which indicates that those policies will be excluded. In this case, only the B () method of Class A is executed because he is the only test method that belongs to the slowtests policy and does not belong to the fasttests policy.
As we can see from the above two examples, the A () method of Class A is never executed because it does not belong to any policy.
5. Command line run JUnit test
By using the Org.junit.runner.JUnitCore class, you can run test cases outside of Eclipse. This class provides the Runclasses () method that allows you to execute one or more test classes. The return type of the Runclasses () method is a Org.junit.runner.Result object. The object can collect information for all tests. If you have failed test cases, you can use the Org.junit.runner.notification.Failure object to get a description of the failed test case.
The process below shows how to run your tests outside of Eclipse. The
creates a new class Junitrunner.java as follows:
Junitrunner.java
We choose to run a test class named Assertionstest.
? Open the DOS window and navigate to the directory where the Junitrunner.java is located (Translator Note: My directory is **\junitguide\test\com\javacodegeeks\junit).
? Compile the test class and the runner class.
Javac-classpath "D:\learnTech\test\junit-4.11.jar"; " D:\learnTech\test\hamcrest-core-1.3.0.jar "; Assertionstest.java Junitrunner.java
As in eclipse, we need to include the JUnit jar package in the classpath. Run through the above command. In the directory where Junitrunner.java is located, the Assertionstest.class and Junitrunner.class two class files are generated. As shown below:
? In the DOS window, go back to the test source directory (Translator Note: My directory is **\junitguide\test).
? Run the Junitrunner class.
Java-classpath "D:\learnTech\test\junit-4.11.jar"; " D:\learnTech\test\hamcrest-core-1.3.0.jar "; Junitrunner
Outputs the result:
JUnit Unit Test Tutorial (translated from Java Code Geeks)