Using JUnit in Eclipse

Source: Internet
Author: User
Tags assert

Using JUnit unit tests can reduce the production of project bugs to some extent. Many times, we are in the main function alone to test a method, such a test is very inconvenient. Using JUnit can be a test unit and project code separation, test multiple methods at once, and evaluate the results.

For unit testing in Eclipse, the process is to add the JUnit class library to the right-click Project-"Build path" add library. Then right-click the project and add a source folder named Test.

The following code comes as far as

First create a new class.


Package Com.dong.util;public class Calculate {public int add (int a, int b) {return a + B;} public int subtract (int a, int b) {return a-A;} public int mutiply (int a, int b) {return a * b;} public int divide (int a, int b) {return a/b;}}

We can then right-click the class to generate a JUnit test case. This generates a test class.


Package Com.dong.util;import static Org.junit.assert.assertequals;import Org.junit.test;public class CalculateTest {/ /@Test//public void Test () {//fail ("not yet implemented"),//} @Testpublic void Testadd () {assertequals (6, New Calculate (). Add (3, 3));} @Testpublic void Testsubtract () {assertequals (0, New Calculate (). Subtract (3, 3));} @Testpublic void Testmutiply () {assertequals (9, New Calculate (). Mutiply (3, 3));} @Testpublic void Testdivide () {assertequals (1, New Calculate (). Divide (3, 3));}}

The test class is in fact under the same package name as the tested class, except under a different source folder. The above test sample is the simplest example, just called the Assertequal method, and more test methods can be found in the documentation.

Here are some requirements for the Test class.

    • 1 test methods must be decorated with @test
    • 2 test methods must use the public void method, with no parameters
    • 3 Create a new source code directory to store the test code
    • 4 The package for the test class should be consistent with the class being tested
    • 5 Each method of the test unit must be independently tested and the test method cannot be dependent
    • 6 test class uses test as the class name most (not required)
    • 7 test methods use test as a prefix (not required)

The following class shows the order in which the JUnit tests invoke each method.


package com.dong.util;import static Org.junit.assert.assertequals;import Org.junit.after;import Org.junit.afterclass;import Org.junit.before;import Org.junit.beforeclass;import Org.junit.test;public class Junitflowtest {/** * All methods are executed before being called. Because it is static, it is suitable for content that is loaded only once. For example config file * * @throws Exception */@BeforeClasspublic static void Setupbeforeclass () throws Exception {System.out.println ("@B Eforeclass ");} /** * Resource Cleanup * * @throws Exception */@AfterClasspublic static void Teardownafterclass () throws Exception {System.out.printl N ("@AfterClass");} /** * Method Executes before * * @throws Exception */@Beforepublic void SetUp () throws Exception {System.out.println ("@ @Before");} /** * Method After execution * * @throws Exception */@Afterpublic void TearDown () throws Exception {System.out.println ("@ @After");} @Testpublic void Testadd () {System.out.println ("Testadd"); Assertequals (5, New Calculate (). Add (3, 3));} @Testpublic void Testmutiply () {assertequals (9, New Calculate (). Mutiply (3, 3));}} 
@BeforeClass represents the action that was taken before the method used to test the class test.
@AfterClass represents the action that the test class performs after all methods have been tested.
@Before represents the action that is taken before each test method is executed.
@After represents the action that is taken after each test method is executed.
The following class shows the ways in which some commonly used test annotations are used.

package com.dong.util;import static Org.junit.assert.assertequals;import Org.junit.ignore;import org.junit.test;/** * JUnit Annotations * * @author * */public class Anotationtest {/** * @Test set a normal method to Test method * @Test (expected = Arithmeticexception.class) indicates that an exception is expected to be thrown * @Test (timeout= milliseconds) test dead loop and performance test * @BeforeClass all methods executed before execution * @  Afterclass all methods execute after execution * @Before Each method executes before execution * @After execute after each method execution * @Ignore ignored * @RunWith You can change the test runner Org.junit.runner.Runner *//** * @Test (expected = Arithmeticexception.class) indicates that an exception is expected to be thrown */@Testpublic void Testdivide () {assertequals (1, New Calculate (). Divide (3, 0));} /** * @Test (timeout= ms) test dead Loop and performance test */@Ignore @Test (timeout = $) public void Testwhile () {while (true) {assertequals (1, NE W Calculate (). Divide (3, 3));}} @Test (timeout = n) public void Testreadfile () {try {thread.sleep ()} catch (Interruptedexception e) {//TODO Auto-ge Nerated catch Blocke.printstacktrace ();}}} 

In some cases, it may be necessary to test multiple test cases at the same time, which can be cumbersome if you write an assert every time. For example, when we want to test the addition, there are 2 examples of 1+2. =3  ,2+2? = 4. It can be implemented using the following code.

Package Com.dong.util;import static Org.junit.assert.assertequals;import Java.util.arrays;import Java.util.collection;import Org.junit.test;import Org.junit.runner.runwith;import org.junit.runners.Parameterized ; Import org.junit.runners.Parameterized.Parameters; @RunWith (parameterized.class) public class Parametertest {/** * 1 Change the default test run period of @runwith (PARAMETERIZED.CLASS) 2 declare variable to hold the expected value and result value * 3 Declare a public static method with a return value of collection and use the @parameters modifier * 4 declare a public constructor with parameters for the test class and declare the variable in it */int expected = 0;int INPUT1 = 0;int input2 = 0; @Parameterspublic static collection< Object[]> T () {return arrays.aslist (new object[][] {{3, 1, 2}, {4, 2, 2}}); Public parametertest (int expected, int input1, int input2) {super (); this.expected = EXPECTED;THIS.INPUT1 = input1; Put2 = Input2;} @Testpublic void Testadd () {assertequals (expected, new Calculate (). Add (INPUT1, Input2));}}

We can use the suite when we want to run several test classes that we've developed at once. Use the following method.


/** * Test Kit * * @author * * */  @RunWith (suite.class)//test suite Entry class, run multiple classes @suite.suiteclasses at once ({tasttest.class, TastTest1 . class, Tasttest4.class}) public class Suitetest {/** * 1, test suites are run with the organization Test class * * Write a portal class as a test suite, this class does not contain other methods to change the test class run time The class that will be tested is passed as an array to Suite.suiteclass ({}) */}



Using JUnit in Eclipse

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.