Unit Testing with JUnit 4.x and easymock in eclipse-tutorial

Source: Internet
Author: User
ArticleDirectory
    • Summary
    • 1.1. Unit Test
    • 1.2. Installation
    • 2.1. Overview
    • 2.2. compile your first unit test
    • 2.3. Run your unit test in eclipse
    • 3.1. Preparation
    • 3.2. Create a class to be tested
    • 3.3. Create a test class
    • 3.4. Create a Test Set
    • 4.1. Setup () and teardown ()
    • 4.2. use static imports in eclipse
    • 4.3. Annotations
    • 4.4. Assert statement
    • 5.1. Easy mock Overview
    • 5.2. Using JUnit and easy mock

Address: http://www.vogella.de/articles/JUnit/article.html

This article address: blog Park Jing Han Jing http://gpcuster.cnblogs.com

Translation:

Use junit4.x and easymock in eclipse for unit test summary

This article briefly explains how to use JUnit 4.x and easymock for unit testing in eclipse.

After reading this article, you can use JUnit in eclipse for unit testing.

1. Summary 1.1. Unit Test

The unit test developer writes to test a function.Code. Unit Testing can ensureProgram.

JUnit 4.x is an automated testing framework first written by Erich Gamma and Kent Beck. It uses the Annotation Feature of Java to mark the methods to be tested.

In JUnit, there is a very important Convention: All test cases should not depend on other test cases.

1.2. Installation

Download junit4.x. jar on the official website of JUnit and add it to classpath.

In the current eclipse version, JUnit has been integrated and can be directly used.

2. How to Write unit test 2.1. Overview

JUnit uses annotations to differentiate the methods to be tested.

Compile a test case:

    • Add Annotations: @ org. JUnit. test to the method to be tested.

    • If you want to check whether two objects are equal, use org. JUnit. Assert. * And call assertequals ().

Static imports is valid in Java 5.0 or later versions, such as: Import static org. JUnit. Assert .*

2.2. compile your first unit test

Write Java code:

 package gpcuster.cnblogs.com; 
Import static Org. JUnit. assert. assertequals;
Import Org. JUnit. test;
Public class myfirstjunittest {
@ test
Public void simpleadd () {
int result = 1;
int expected = 1;
assertequals (result, expected );
}< BR >}
2.3. Run your unit test in eclipse

On the eclipse menu bar, choose run as-> JUnit test.

Eclipse displays the running result through the green and red status bars.

3. Use junit3.1. in eclipse to prepare

Create a new project "De. vogella. JUnit. junittest ". Add a lib directory and add junit4.jar to classpath. If you want to know how to add classpath, view adding an external library to the Java classpath in eclipse.

Then create a testSource codeFolder, as shown in:

Click "add folder" and then "create new folder ". Create a new file directory named "test ".

3.2. Create a class to be tested

Create a package named "gpcuster.cnblog.com ".

Create a class "myclass" in the package "gpcuster.cnblog.com". The Code is as follows:

 
Package gpcuster.cnblogs.com;

Public ClassMyclass {
Public IntMultiply (IntX,IntY ){
ReturnX/y;
}
}
3.3. Create a test class

Select the class you want to test, operate new-> JUnit test case, and then select "New JUnit 4 test ":

If you haven't put JUnit in your classpath, eclipse will ask you if you want to add it to classpath:

The code for the test class is as follows:

 Import  static  Org. JUnit. assert. assertequals; 
Import Org. JUnit. test;
Public class myclasstest {
@ test
Public void testmultiply () {
myclass tester = New myclass ();
assertequals ( "result" , 50, tester. multiply (10, 5);

}< BR >}

Right-click the test class and select Run-as-> JUnit test.

Test results, you can modify the problems in the code and then run it again. If it succeeds, a green status bar is displayed.

3.4. Create a Test Set

If you need many test cases, you can create a test set that contains all the test cases to be tested.

Option to test the class, and then right-click: New-> Other-> JUnit-test suite

The created code is as follows:

 
Package gpcuster.cnblogs.com;

Import org. JUnit. Runner. runwith;
Import org. JUnit. Runners. Suite;

@ Runwith (suite.Class)
@ Suite. suiteclasses ({myclasstest.Class})
Public ClassAlltests {
}
4. Learn more about junit4.1. setup () and teardown ()

For each test case, You can implement setup () and teardown (). Setup are called during the initialization of each test case. Teardown () is called at the end of each test case.

4.2. use static imports in eclipse

The static method is widely used in JUnit.

Eclipse cannot automatically import static imports.

You need to import 'org. JUnit. Assert 'to Java> editor> content assist> favorites. After you do this, you can use content assist (CTRL + space) to add a method.

4.3. Annotations

The use of annotations in JUnit 4.x is as follows:

Annotation Description

@ Test public void method ()

Method to be tested.

@ Before public void method ()

The method to be called before each test case is executed.

@ After public void method ()

The method to be called after each test case is executed.

@ Beforeclass public void method ()

Methods To be called before all test cases are executed.

@ Afterclass public void method ()

The method to be called after all test cases are executed.

@ Ignore

Ignore the test method.

@ Test (expected = illegalargumentexception. Class)

The specified exception is expected to be thrown in the test case.

@ Test (timeout = 100)

The expected execution time of the test case.

Table 1. Annotations

4.4. Assert statement

The use of assert statements in JUnit 4.x is as follows:

Assert statement Description

Fail (string)

Method failed.

Asserttrue (true)

Check whether it is true.

Assertsequals ([String message], expected, actual)

Checks whether two objects are equal.

Assertsequals ([String message], expected, actual, tolerance)

Checks whether two objects are equal within the allowed precision range.

Assertnull ([Message], object)

Check whether it is empty.

Assertnotnull ([Message], object)

Check whether it is empty.

Assertsame ([String], expected, actual)

Checks whether two objects are an object.

Assertnotsame ([String], expected, actual)

Checks whether two objects are not one.

Asserttrue ([Message], Boolean condition)

Check whether it is true.

Try {A. shouldthroughexception (); fail ("failed")} catch (runtimeexception e) {asserttrue (true );}

Checks whether an exception is thrown.

Table 2. Assert statements

5. Easy mock5.1. overview of easy mock

The previous example is very simple, but in the actual environment, the classes we need to test may depend on other third-party libraries.

Therefore, to test our classes, we need to simulate or control other third-party libraries. The best solution is to create a mock object. Mock objects can be written or generated by easymock.

The mock object is an empty interface. You can fully control all the actions of the object implementing the interface.

5.2. Using JUnit and easy mock

Download easymock and add easymock. jar to your classpath.

Create a Java project javamocktest. Create these classes in the following code. Incomecalculator needs to be tested.

Package income;

Public Enum Position {
Boss, programmer, surfer
}


Package income. exceptions;

Public Class Positionexception extends runtimeexception {

Private Static Final Long Serialversionuid = 1l;

Public Positionexception (string message ){
Super (Message );
}
}


Package income. exceptions;

Public Class Calcmethodexception extends runtimeexception {

Private Static Final Long Serialversionuid = 1l;

Public Calcmethodexception (string message ){
Super (Message );
}
}


Package income. method;

Import income. position;

Public Interface Icalcmethod {

Public Abstract Double Calc (position );

}

Package income;

Import income. Exceptions. calcmethodexception;
Import income. Exceptions. positionexception;
Import income. method. icalcmethod;


Public Class Incomecalculator {

Private Icalcmethod calcmethod;
Private Position position;

Public Void Setcalcmethod (icalcmethod calcmethod ){
This . Calcmethod = calcmethod;
}
Public Void Setposition (position ){
This . Position = position;
}
Public Double Calc (){
If (Calcmethod = Null ){
Throw New Calcmethodexception ( "Calcmethod not yet maintained" );
}
If (Position = Null ){
Throw New Positionexception ( "Position not yet maintained" );
}
Return Calcmethod. Calc (position );
}
}

We use easymock in JUnit for testing:

Package income;

Import Static Org. JUnit. Assert. assertequals;
Import Static Org. JUnit. Assert. fail;
Import income. Exceptions. calcmethodexception;
Import income. Exceptions. positionexception;
Import income. method. icalcmethod;

Import org. easymock. easymock;
Import org. JUnit. before;
Import org. JUnit. test;

Public Class Incomecalculatortest {

Private Icalcmethod calcmethod;
Private Incomecalculator calc;

@ Before
Public Void Setup () throws exception {
Calcmethod = easymock. createmock (icalcmethod. Class );
Calc = New Incomecalculator ();
}

@ Test
Public Void Testcalc1 (){
// Setting up the expected value of the method call calc Easymock. until CT (calcmethod. calc (position. boss )). andreturn (70000.0 ). times (2); easymock. until CT (calcmethod. calc (position. programmer )). andreturn (50000.0 );// Setup is finished need to activate the mock Easymock. Replay (calcmethod); Calc. setcalcmethod (calcmethod ); Try {
Calc. Calc ();
Fail ( "Exception did not occur" );
} Catch (Positionexception e ){

}
Calc. setposition (position. Boss );
Assertequals (70000.0, Calc. Calc ());
Assertequals (70000.0, Calc. Calc ());
Calc. setposition (position. programmer );
Assertequals (50000.0, Calc. Calc ());
Calc. setposition (position. surfer );
Easymock. Verify (calcmethod );
}

@ Test (expected = calcmethodexception. Class )
Public Void Testnocalc (){
Calc. setposition (position. surfer );
Calc. Calc ();
}

@ Test (expected = positionexception. Class )
Public Void Testnoposition (){
Easymock. Wrong CT (calcmethod. Calc (position. Boss). andreturn (70000.0 );
Easymock. Replay (calcmethod );
Calc. setcalcmethod (calcmethod );
Calc. Calc ();
}

@ Test (expected = positionexception. Class )
Public Void Testcalc2 (){
// Setting up the expected value of the method call calc Easymock. Expect (calcmethod. Calc (position. surfer). andthrow ( New Positionexception ( "Don't know this guy" ). Times (1 );

// Setup is finished need to activate the mock Easymock. Replay (calcmethod); Calc. setposition (position. surfer); Calc. setcalcmethod (calcmethod); Calc. Calc ();}}

The round CT method tells us that the mock object returns a specific value for a special parameter.

We need to call the reply method to make our mock object valid.

When the call ends, you can call the verify method to check whether the mock object is called.

Address: http://www.vogella.de/articles/JUnit/article.html

This article address: blog Park Jing Han Jing http://gpcuster.cnblogs.com

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: 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.