How to use eclipse for junit testing

I. Introduction

JUnit is an open source regression testing framework written by Erich Gamma (author of design pattern) and Kent Beck (supporter of extreme programming) for Java coders to do unit testing. The current version is 4. 1, which can be obtained from www.junit.org website. Compared with the early JUnit 3, JUnit 4. 1 depends on the new features of Java 5.0, so it is not compatible with jdk 1.4, which can be said to be a brand-new framework.

Because the IDE used here is Eclipse 3.2. 1 plus language package, which integrates junit 4. 1, it saves the trouble of downloading the configuration class library.

Second, create a project.

Open Eclipse and click File->; "new"->; The Project or New button opens the New dialog box:

Please select "Java Project" and click "Next" to enter the "New Java Project" dialog box:

In this dialog box, you need to set the name of the project and the directory where the project is located. I named my project JUnitTest, and the directory is F: \ ypjcck \ JUnit \ Eclipse \ JUnit test. Since Eclipse comes with JUnit class library, just click Finish at this time.

Third, write JavaBean for testing.

The JavaBean used for the test is very simple, named Book, with only two attributes, id and name, which will be used in two use cases respectively. Let's start writing JavaBean.

Please click "file"->; "new"->; Class, open the "New Java Class" dialog box, set the package to net.test.unit.junit, set the name to Book, and make sure that the "public static void main (string [] args)" option is not selected, and then click Finish. Modify the code as follows:

Package net.test.unit.junit;

Public books {

Private string id = null

Private string name = null

Public string getId() {

Return id;

}

Public void setId (string id)

this.id = id

}

Public string getName() {

Returns the name;

}

Publicvoid collection name (string name) (

this.name = name

}

}

At this point, the JavaBean for testing is completed.

Fourth, write test cases.

Only one class is used for testing here, and this class is called BookTest. In the past, classes like this needed to inherit junit.framework.TestCase, but JUnit 4. 1 made full use of the new annotation function in Java 5.0, so there was no need to do so. Of course, JUnit 4. 1 still provides support for the old method, but I don't intend to introduce it here.

The BookTest class contains two use cases, which correspond to the caseId and caseName methods of this class, that is, each method implements one use case. Different from JUnit 3.8. 1, in JUnit 4. 1, the method name is no longer required to start with test, but is allowed to be named at will, as long as it conforms to the naming specification of Java. Here, in order to illustrate this point, the case is specially used as the beginning, but the test case must be marked with @Test. In addition, BookTest has two methods: setUp and tearDown, marked with @Before and @After respectively. The former is executed before each test method and is mainly used for initialization. The latter is executed after each test method is completed, and is mainly used to clean up resources. Note that the naming of these two methods is also unlimited, and there is no limit to the number of definitions, but they must be marked with @Before and @After. In addition, JUnit 4. 1 also provides annotations @BeforeClass and @AfterClass, which are similar in function to @Before and @After, but the former is used to initialize and clean up before all use cases are executed, and the latter is used to initialize and clean up before each use case is executed. Let's start writing BookTest.

In Eclipse, there are two ways to create a BookTest class: first, click "file"-> as before to create a Book class; "new"->; "Class" to create; Method 2: first select the Book class in the package browser, and then click file->; "new"->; "JUnit test case", open the "New JUint Test Case" window:

At this point, you will find that a lot of information has been automatically added by Eclipse. If you want to use Eclipse to automatically create test methods, click Next. Since this article will write the test method by itself, please click "Finish" directly.

After creating the BookTest class, modify the code as follows:

Package net.test.unit.junit;

Import static org.junit.assert. *;

Import org.junit.after;

Import org.junit.before;

Import org.junit.test;

Public course book test (

Book book = null

@ Before

The public void setting () threw an exception {

System.out.println ("Test begins!" );

Book = new book ();

System.out.println("book object initialization! " );

}

After @

Public void tearDown () threw an exception {

System.out.println("book object will be cleaned up! " );

book = null

System.out.println ("Test is over!" );

}

@ Test

Public void caseId() {

book . setid(" 00 1 "); //Set the value of the id attribute to 00 1.

//Use Assert to check whether the value of the id attribute is 00 1.

assertEquals("00 1 ",book . getid());

System.out.println("id attribute tested! " );

}

@ Test

Public void caseName() {

book . setname(" ASP "); //Set the value of the name property to ASP.

//Use Assert to check whether the value of the name attribute is JSP, which is an error-bound test.

assertEquals("JSP ",book . getname());

System.out.println("name property tested! " );

}

}

The setUp and tearDown methods here are not mentioned, but the book object is initialized and cleaned up, but caseId and caseName need to be explained. The former is the id attribute of the test book, which is assigned as "00 1" first, and then the value stored in the id attribute is checked whether it is the expected value by the assertEquals method. Since my expected value is also "00 1", this use case should be successful after execution. The latter is the name attribute of the test book, and it is also assigned as "ASP" first, and then the assertEquals method is used to see if its value is the expected value. Because I deliberately set the expected value to "JSP", there will be an error after this use case is executed.

The AssertEquals method is a static method of the assert class. At the beginning of the program, there is a line of code, "import static org. JUnit.assert. *;" Use the static import provided by Java 5.0 to import the Assert class statically, so that we can directly use any static method of the Assert class in the program. Let's briefly introduce the static class org.junit.Assert

This category mainly includes 8 categories and 22 methods, as follows:

1.AssertEquals (), 8 overload, used to check whether the value stored in the object is the expected value, similar to the Equals () method used in string comparison;

2.Assertifalse () and Assertitrue () each have two overloads to check whether the variable is false or true. If the value of the variable checked by Assertifalse () is false, the test succeeds, if it is true, the test fails, and Assertitrue () is the opposite;

3.AssertSame () and assertNotSame (), two overloads each, are used to compare whether the references of two objects are equal, similar to using "= =" and "! = "Compare two objects;

4.Assert null () and assertNotNull () each have two overloads to check whether the object is empty;

5.fail (), two overloads, meaning failure, is used to throw an error. Personally, I think there are two purposes: first, in test-driven development, because the test case is written before the tested class, it is not clear whether it is correct or not when it is written, so we can use fail method to throw errors for simulation; The second is to throw an unexpected error. For example, the content to be tested is whether the data read from the database is correct, but the reason for the error is that the database connection failed.

5. run BookTest.

After writing BookTest, you can run it. Click the inverted triangle next to the Run button, and then select Run By-> "1 JUnit test", the running effect at this time is as follows:

You can see the "JUnit" column on the left side of the picture, which contains errors. However, this error is expected. If you don't want to read it, you can change "JSP" in the testName () method to "ASP", and the running effect is as follows:

At this point, you will see that the progress bar in the JUnit column is not red, but green, which indicates that there are no errors.

Intransitive verb test set

When you need to test multiple test classes at the same time, you should use the test suite to complete the work. However, the test suite creation function provided by Eclipse 3.2. 1 does not support JUnit 4. 1 well, so we have to create it manually.

Click "file"->; "new"->; Class to create a class named AllTests, as follows:

Click Finish to modify the code as follows:

Package net.test.unit.junit;

Import org.junit.runner.runwith;

Import org.junit.runners.suite;

@RunWith(Suite.class)

@Suite。 SuiteClasses(BookTest.class)

Common Class All Tests {}

Here, AllTests is an empty class, annotated with @RunWith and @ suite. Take the class BookTest to be tested as the parameter of annotation of @ Suite.Suiteclaces, and then set the test suite suite as the parameter to runner @RunWith. You can select the file below and click Run As-> 1 JUnit test.

Please note that the @ suite.suiteclaces annotation supports arrays, for example:

@Suite。 SuiteClasses ({BookTest.class,BookTest2.class })

This allows you to run multiple test classes at once.

Seven, under the command line

The operation modes described above are all based on Eclipse. In fact, JUnit itself provides a way to execute the following commands on the command line:

The folder where java -cp junit-4. 1.jar is located; org.junit.runner.JUnitCore

Net. test. unit. JUnit. all test

If you want to run multiple test classes, as follows:

The folder where java -cp junit-4. 1.jar is located; org.junit.runner.JUnitCore

All tests

Eight, JUnit using advanced

@Ignore comment, ignore test, used to ignore test cases that you don't want to run for the time being. Take BookTest as an example, add a reference "importorg.junit.ignore; At the beginning of the file. , and then modify the caseName method:

Ignore

@ Test

public void caseName()

Click "operation mode"->; "1 JUnit test", the running effect is as follows:

At this point, the caseName () method has been ignored.

The expected parameter exception test of the @Test annotation is used to test whether the specified exception will be thrown. Throwing is success, throwing is failure. Please add a test case in BookTest:

@Test (should be = ArithmeticException.class)

public void caseException() {

int n = 2/0;

}

This test case is divided by 0, and the running effect is as follows:

Success! Because the specified ArithmeticException was thrown.

The timeout parameter of @Test annotation is a time-limited test, which is used to limit the time consumed by test cases, in milliseconds. If the test case is not completed within the limited time, it is a failure, otherwise the execution result of the test case shall prevail. Please add a test case in BookTest:

@Test(timeout= 1000)

public void caseWhile() {

for(; ; ) {

}

}

This is an infinite loop, and it will stop forcibly after 1 second. The operation effect is as follows:

The operation failed due to timeout.

@Parameters annotation, parameter test, used to test a set of data of the same test case. Please create a new "JUnit test case" BookTest2 and modify the code as follows:

Package net.test.unit.junit;

Import static org.junit.assert.assertequals;

Import java.util.arrays;

Import java.util.collection;

Import org.junit.after;

Import org.junit.before;

Import org.junit.test;

Import org.junit.runner.runwith;

Import org.junit.runners.parameterized;

Import org.junit.runners.parameterized.parameters;

@RunWith(Parameterized.class)

Public Book Test 2 {

Id is required for private string;

Private string targetId

Private string requires name;;

Private string targetName

Book book = null

@ parameter

Public static collection result () {

Return Arrays.asList (new object [] [] {

{ "002 "," 00 1 "," JSP "," ASP" },

{ "00 1 "," 00 1 "," ASP "," ASP" }

});

}

public book test 2(String expected id,String targetId,String expectedName,String targetName) {

this . expected id = expected id;

this.targetId = targetId

this . expected name = expected name;

this . target name = target name;

}

@ Before

The public void setting () threw an exception {

System.out.println ("Test begins!" );

Book = new book ();

System.out.println("book object initialization! " );

}

After @

Public void tearDown () threw an exception {

System.out.println("book object will be cleaned up! " );

book = null

System.out.println ("Test is over!" );

}

@ Test

Public void caseId() {

book . setid(targetId); //Set the value of the id attribute.

//use Assert to view the value of the id attribute.

assertEquals(expectedId,book . getid());

System.out.println("id attribute tested! " );

}

@ Test

public void caseNames() {

book . set name(target name); //Set the value of the name property.

//Use Assert to view the value of the name property.

assertEquals(expectedName,book . getname());

System.out.println("name property tested! " );

}

}

This example is actually an extended version of BookTest, but there are several changes on the original basis:

First, add a line of code at the file header: @RunWith(Parameterized.class), which is used to call the BookTest2 class to run;

Secondly, define a result static method annotated with @Parameters to store test data. In this example, two sets of data, four in each set, are stored.

Thirdly, a constructor with parameters is defined, and the number of parameters is equal to the number of each group of test data.

Finally, four member variables, such as expectedId, are defined to pass the test data to the test case.

BookTest2 is executed below, and the running effect is as follows:

The test case was run twice, the first time it failed because the expected value was not equal to the set value, and the second time it succeeded.

JUnit. Framework. JUnit 4 Test Adapter relies on the new features of Java 5.0, and JUnit 4. 1 of junit.framework.TestCase has been introduced for some time, but some IDE with JUnit test environment, such as NetBeans 5.5 and even the old Eclipse, still only support JUnit 3. The test cases developed based on JUnit 4. 1 environment can't run correctly, so to solve this problem, we need to use JUnit.framework.JUnit 4 to test the adapter class. Create a new class TestSuite and modify the code as follows:

Package net.test.unit.junit;

Common class test suite {

public static void main(String[]args){

JUnit . textui . test runner . run(test suite . suite());

}

public static JUnit . framework . test suite(){

Returns newjunit.framework.junit4testadapter (alltests.class);

}

}

The most important one is the suite method, which enables all Tests classes created based on JUnit 4 environment to run in JUnit 3 command line environment through JUnit. Frame. JUnit 4 tests the adapter class.