JUnit Foundation and first unit test instance (JUnit3.8)

Source: Internet
Author: User
Tags assert documentation reflection

Unit Test

  Unit Testing refers to the inspection and validation of the smallest testable unit in the software.

Unit tests are not meant to prove that you are right, but to prove that you have no errors.

Unit testing is primarily used to determine whether the execution of a program is consistent with the results you expect.

The key is the test case used.

JUnit

JUnit is a unit test framework for the Java language.

Project home: http://junit.org/

Many Ides in Java, such as Eclipse integration JUnit, simply need to add a library to the build path and select the version you want to use.

The two major versions of JUnit are JUnit 3.8 and JUnit 4, which use reflection, which uses reflection and annotations.

Post review: The last time this blog introduced JUnit was after reflection and annotations:

Http://www.cnblogs.com/mengdd/archive/2013/02/02/2890204.html

   combine examples to illustrate the use of unit tests: 1. Writing the target class source code

Create a new project, named Junittest, first write a target class calculator:

Package com.mengdd.junit;

public class Calculator
{public
    int Add (int a, int b)
    {
        return a + b;
    }
    
    public int subtract (int a, int b)
    {return a-a
        ;
    }
    
    public int multiply (int a, int b)
    {
        return a * b;
    }

    public int divide (int a, int b)
    {
        return a/b;
    }
}

2. Add the JUnit library

Then in order to use JUnit, you need to join the library:

Right-click on the project properties-> left Java Build path-> tag Libraries->add Library ...

The popup dialog selects JUnit, then Next, and then JUnit 3 or JUnit 4.

This example selects JUnit 3.

3. Create a test class

Here are a few things to keep in mind:

  1. Best Practices for using JUnit: source code and test code need to be separated.

Therefore, you can create a new source folder named Test, which is used to store the code of the testing class. This allows the program to be tested when the program is released and can be discarded.

However, the class files compiled by the classes in both folders will be in the same bin folder.

  2. The classes that test the class and the target source code should be under the same package, i.e. their package names should be the same.

In this way, you do not have to import the package that contains the source code in your test class, because they are located under the same package.

  3. Naming rules for test classes :

Add test before or after the class name to be tested.

After this step is complete, the project directory is as follows:

  

4. Test Class Code writing

The test class must inherit from the TestCase class.

TestCase Document Description:

Public abstract class TestCase
Extends Assert
Implements Test


A test case defines the fixture to run multiple tests.

To define a test case
1) Implement a subclass of TestCase
2) Define instance variables that store the state of the fixture
3) Initialize the fixture state by overriding SetUp
4) clean-up after a test by overriding TearDown.
Each test runs in it own fixture so there can be no side effects among test runs.

(in the final resources of this article, you will see a web-link to the JUnit documentation, which you may need to download)

There is also an important assert class, see documentation, which is all static void methods.

requirements for methods in the test class:

In JUnit 3.8, the test method needs to meet the following principles:

1.public.

2.void.

3. No method parameters.

4. The method name must begin with test. (it finds all the methods by reflection and then finds the method that starts with test).

It is important to maintain full independence between Test case and not allow any dependencies.

Removing some of the methods will have no effect on other methods.

We cannot rely on the execution order of the test methods.

In summary, write the following code:

Package com.mengdd.junit;
Import Junit.framework.Assert;

Import Junit.framework.TestCase; public class Calculatortest extends TestCase {public void Testadd () {Calculator Calculator = new Calcula
        Tor ();
        int result = Calculator.add (1, 2);
        The return result of the method is Assert.assertequals (3, result);//The first parameter is expected, the second argument is the value to validate} public void Testsubtract () {
        Calculator Calculator = new Calculator ();
        int result = Calculator.subtract (1, 2); 
        The return result of the method is Assert.assertequals ( -1, result);//The first parameter is expected, the second argument is the value to validate} public void Testmultiply () {
        Calculator Calculator = new Calculator ();
        int result = Calculator.multiply (2, 3);
        The return result of the method is assert.assertequals (6, result);//The first parameter is expected, the second argument is the value to validate} public void Testdivide () {
        Calculator Calculator = new Calculator ();
        int result = Calculator.divide (12, 3); Assert.assertequals (4, RES) of the return result of the judging methodULT);//The first parameter is expected, the second argument is the value to validate}} 

Run: Right-Select the class, run As->junit Test

(You can right-select run to run repeatedly here)

JUnit slogan: Keep the bar green to Keep the code clean. 5. Code refactoring: Using the SetUp () method

There is a principle:DRY (Don ' t Repeat yourself)

So refactor the code and place the duplicated part of the generated object in the Setup () method.

(When overridden, the protected becomes public, and it is no problem to extend the scope of access when inheriting.) )

Test the test for a method first:

Add the following code to the Calculatortest class:

    @Override public
    void SetUp () throws Exception
    {
        System.out.println ("Set up");
    }
    
    @Override public
    void TearDown () throws Exception
    {
        System.out.println (' Tear down ');
    }

After running again, find the output in the console as follows:

Describes the two methods that were executed several times.

  the setup () is executed before each test case, and TearDown () executes after each test case executes.

  that is, for each test case, the order of execution is:

1.setUp ()

2.testXXX ()

3.tearDown ()

Refactoring: Generate objects using member variables (in order to be used in each method), place the statements of the generated objects in Setup (), and note that each test case will generate new objects.

After refactoring the code is as follows:

Package com.mengdd.junit;

Import Junit.framework.Assert;
Import Junit.framework.TestCase;

public class Calculatortest extends TestCase
{

    

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: info-contact@alibabacloud.com 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.