Junit4 is the biggest improvement in JUnit framework history, so friends who have never used JUnit and friends who have never used junit4. Let's get started with the speed of light (* ^__ ^ *)
Prepare the class to be tested
Create a Java project named myproject
Create a class named caculater
The Code is as follows:
Public class caculater {
Public int add (int A, int B ){
Return A + B;
}
Public int Delete (int A, int B ){
Return A; // intentionally incorrect
}
Public int multiply (int A, int B ){
Return a * B;
}
Public int divide (int A, int B ){
Return A/B;
}
}
Import package
First, prepare the JUnit. jar package.
Then, let's import the JUnit. jar package to the project:
Right-click the project and choose Properties, Java build path, and libraries. Click addlibraries, select JUnit, click "Next", and select junit4 in JUnit library version, click Finish and click OK.
So that we can add junit4 software package to our project and use junit4 in this project.
Generate the framework to be tested
Right-click the project, new, other, JUnit, and JUnit test case
Name is your own name. It's called myjunit.
Class under test writes caculater, which is the class to be tested.
After you click "Next", the system will automatically list the methods contained in your class and select the method you want to test. In this example, we test the four methods: add, subtract, multiply, and divide. Click Finish.
Write test code
With the framework, we began to write test code in the framework.
By the way, when the framework is generated, each test method contains a sentence "fail (" not yet implemented "); // todo", which means that if this sentence is executed, this test method is equivalent to detecting a problem. We can change it so that we can execute this sentence only when the result is not what we expect.
Code:
Import static org. JUnit. Assert .*;
Import org. JUnit. before;
Import org. JUnit. test;
Public class myjunit {
Caculater c = new caculater ();
@ Test
Public void testadd (){
If (C. Add (1, 1) = 2)
System. Out. println ("");
Else
Fail ("not yet implemented"); // todo
}
@ Test
Public void testdelete (){
If (C. Delete (1, 1) = 0)
System. Out. println ("");
Else
Fail ("not yet implemented"); // todo
}
@ Test
Public void testmultiply (){
If (C. Add (2, 2) = 4)
System. Out. println ("");
Else
Fail ("not yet implemented"); // todo
}
@ Test
Public void testdivide (){
If (C. Add (4, 2) = 2)
System. Out. println ("");
Else
Fail ("not yet implemented"); // todo
}
}
Run the test
It's not easy. Everything is in trouble. Run the test now.
How to run it? Right-click, run as, JUnit test.
There are results,
Sure enough, the divide we intentionally wrote wrong was found to be faulty ~~~ Success!
We will use junit4 for the first time without knowing it. Please try it by yourself (* ^__ ^ *)