Original Address: http://www.work100.net/training/monolithic-frameworks-junit.html
More Tutorials: beam cloud - free course
JUnit
No. | Article section | video |
---|---|---|
1 | TDD | |
2 | JUnit Introduction | |
3 | JUnit Features | |
4 | Examples | |
5 | annotation | |
6 | Affirmation | |
7 | Source code examples |
Please refer above 章节导航
to read
1.TDD
TDD is test-driven development (Test-Driven Development) of the title, is a core agile development practices and technologies, but also a design methodology.
TDD principle is developed before the function code, unit test cases before writing the code, test code to determine what products need to write code. Although TDD is the core practice of Agile methods, but are not suitable for XP (Extreme Programming), it can also be applied to other development methods and processes.
The basic idea of TDD is to promote the testing carried out by the entire development, but test-driven development is not just a simple testing, but the demand analysis, quantitative process design, quality control.
TDD is not just an important purpose test software, testing to ensure the quality of the code is only part of it, but also help customers and programmers need to remove ambiguities in the development process.
First, consider the needs of TDD (objects, functions, processes, interfaces, etc.), mainly on the process of writing test cases framework and interface functions of design, and testing framework can continue to be verified.
2.JUnit Profile
JUnit is an open source testing framework used to write and run repeatable, automated testing, so you can ensure that our code works as expected. JUnit can be widely used for industrial separate Java program and as scaffolds (command line) or IDE (such as IDEA).
JUnit provides:
- Assertion test expected results.
- Test functions share a common test data.
- Test suites easily organize and run the tests.
- Graphics and text test run.
JUnit for testing:
- The whole object
- Part of the object - or some method of interaction methods
- Interaction between several objects (interactive)
3.JUnit Features
- JUnit is an open source framework for writing and running tests.
- It provides annotations to identify test methods.
- Test results are expected to provide assertions.
- It provides a test run test run.
- JUnit tests so you can write code faster and improve quality
- JUnit is elegantly simple. It is not so complicated and does not take too much time.
- JUnit tests can be run automatically, check their results and provide immediate feedback. There is no need to pass the test results are reported to manually comb.
- JUnit tests can be organized into the test suite contains test cases, even other test suites.
- Junit display the progress of the test, the test is no problem if the bar is green, the test fails, it turns red
4. Examples
We still hello-spring
project code demonstrates.
4.1 Update POM
Modify pom.xml
files, increase junit:junit
dependence:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.work100.training.stage2</groupId>
<artifactId>hello-spring</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
4.2. Create a test class
In the test package src/test/java
to create a named MyTest
test class, as follows:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* <p>Title: MyTest</p>
* <p>Description: </p>
*
* @author liuxiaojun
* @date 2020-02-12 15:09
* ------------------- History -------------------
* <date> <author> <desc>
* 2020-02-12 liuxiaojun 初始创建
* -----------------------------------------------
*/
public class MyTest {
/**
* 执行测试方法前执行
*/
@Before
public void before() {
System.out.println("执行 before() 方法");
}
/**
* 执行测试方法后执行
*/
@After
public void after() {
System.out.println("执行 after() 方法");
System.out.println("-------------------------");
}
@Test
public void testSayHi() {
System.out.println("Hi Log4j");
}
@Test
public void testSayHello() {
System.out.println("Hello Log4j");
}
}
5. Notes
annotation | description |
---|---|
@Test public void method() |
Note that the test indicates public void method it is attached can be used as a test case. |
@Before public void method() |
Before annotation indicates, the process must be performed before each test class, in order to perform some of the necessary prerequisites for the test. |
@BeforeClass public static void method() |
BeforeClass comments pointed out that this is attached to the static method must be executed before all the tests and once in class. When this occurs, the test is generally calculated shared configuration (e.g., connect to the database). |
@After public void method() |
After annotation indicates, the method executes (e.g., perform a test reset every certain variables, delete the temporary variables, etc.) after the execution of each test |
@AfterClass public static void method() |
When it is desired to perform all tests performed after JUnit test class, may be used to clean AfterClass annotation creation method (such as disconnected from the database). Note: with this annotation (similar BeforeClass) method must be defined as static. |
@Ignore public static void method() |
When you want to temporarily disable a specific test execution can be used to ignore the comment. Each method is annotated as @Ignore will not be executed. |
6. affirm
6.1. What is asserted
Assertions are programming terms, expressed as the number of Boolean expressions, programmers believe the expression is true at a particular point in the program, you can enable and disable assertions verified at any time, so you can enable assertions at the time of testing and deployment when disable assertions. Likewise, the program put into operation, the end user can re-enable assertions when they encounter problems.
Use assertions can create a more stable and better quality and not prone to error code. When you need a break when the current operation is false, you can use assertions. Unit testing must assert (Junit / JunitX).
6.2. Common assertions
Affirmation | description |
---|---|
void assertEquals([String message], expected value, actual value) |
Assertion two values are equal. There may be value types: int, short, long, byte , char or java.lang.Object. The first parameter is an optional string message |
void assertTrue([String message], boolean condition) |
Assert a condition is true |
void assertFalse([String message],boolean condition) |
Assert a condition is false |
void assertNotNull([String message], java.lang.Object object) |
Assertion of an object is not empty (null) |
void assertNull([String message], java.lang.Object object) |
Assertion of an object is empty (null) |
void assertSame([String message], java.lang.Object expected, java.lang.Object actual) |
It asserts that two objects refer to the same object |
void assertNotSame([String message], java.lang.Object unexpected, java.lang.Object actual) |
It asserts that two objects are not reference the same object |
void assertArrayEquals([String message], expectedArray, resultArray) |
Assert expected results equal arrays and arrays. Type of the array could be: int, long, short, char , byte or java.lang.Object. |
6.3. Test results assertion
TestAssert create a method called before the following code unit test classes:
/**
* 测试断言
*/
@Test
public void testAssert() {
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);
assertArrayEquals(arithmetic1, arithmetic2);
}
Run to see the effect of the assertion:
执行 before() 方法
Hello Log4j
执行 after() 方法
-------------------------
执行 before() 方法
Hi Log4j
执行 after() 方法
-------------------------
执行 before() 方法
执行 after() 方法
-------------------------
java.lang.AssertionError: 为真
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.assertTrue(Assert.java:41)
at MyTest.testAssert(MyTest.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Example 7. Source
Examples of the source has been managed to the following address:
- https://github.com/work100-net/training-stage2/tree/master/hello-spring
- https://gitee.com/work100-net/training-stage2/tree/master/hello-spring
Previous: the Spring
Next: Log4j