JUnit in Action notes

Source: Internet
Author: User

Chapter 2 grouping JUnit
1. JUnit class

Testcase
Testsuite -- designed to run one or more test cases
Basetestrunner -- launches the testsuite

2. Application of composite pattern in JUnit
Both testsuite and testcase implement the test interface. Adding the test object in testsuite means you can add testsuite to run a group of tests, or add testcase to run a test.

Public class testall
{
Public Static Test Suite ()
{
Testsuite suite = new testsuite ("all tests from Part 1 ");
Suite. addtestsuite (testcalculator. Class );
Suite. addtestsuite (testdefacontroller controller. Class );
// If testdefacontroller controller had a suite Method
// (Or alternate suite methods) You coshould also use
// Suite. addtestsuite (testdefacontroller controller. Suite ());
Return suite;
}
}

3. failures and errors
JUnit distinguishes failures and errors.
Failures can be predicted, for example, the failure caused by code changes.
Errors cannot be expected, such as network connection failure.

Chapter 4 examining software tests

Several types of software testing:
1. Unit Test
2. Integration Test
3. Feature test function test use case
4. Stress Test for stress/Load Test
5. Acceptance Test acceptance test

Stress/Load Test Tool
Jmeter http://jakarta.apache.org/jmeter
Junitperf

Code coverage test
Clover http://www.thecortex.net/clover/
Jester

Question:
Can I perform a function test before integration testing? The company's software process is component, which first performs functional testing and then integrates testing.

Chapter 5 automating JUnit

JUnit + ant

There is already a framework for continuous testing: cruisecontrol
Http://blog.csdn.net/chelsea/archive/2004/11/22/190545.aspx

Chapter 6 coarse-grained testing with stubs
Stubs objects

1. Definition
Objects dynamically inserted during runtime to replace the real environment.
Stub-a stub is a portion of code that is inserted at runtime in place of the real code, in order to isolate calling code from the real implementation.

2. Applicability
Coarse granularity

3. Disadvantages
Writing, debugging, and maintenance are too complex.

4. Tools
Jetty (stubbing the web server's resources)
Embedded Server (Embedded Server) can simulate the content of the Web server response by inheriting its resourcehandler class.
Http://jetty.mortbay.org/jetty/index.html

Start Jetty
Httpserver Server = new httpserver ();

Socketlistener listener = new socketlistener ();
Listener. setport (8080); // bind listener to port 8080 to accept the HTTP request
Server. addlistener (listener );

Httpcontext context = new httpcontext ();
Context. setcontextpath ("/");
Context. setresourcebase ("./");
Context. addhandler (New resourcehandler ());
Server. addcontext (context );

Server. Start ();

5. Instance
Code in testcase
Public class testwebclientskeleton extends testcase
{
Protected static httpserver server;

Protected void setup ()
{
Server = new httpserver ();

Socketlistener listener = new socketlistener ();
Listener. setport (8080 );
Server. addlistener (listener );

Httpcontext context1 = new httpcontext ();
Context1.setcontextpath ("/testgetcontentok ");
Context1.addhandler (New testgetcontentokhandler ());
Server. addcontext (context1 );

Server. Start ();
}
Protected void teardown ()
{
Server. Stop ();
}
Public void testgetcontentok () throws exception
{
WebClient client = new WebClient ();
String result = client. getcontent (new URL ("http: // localhost: 8080/testgetcontentok "));
Assertequals ("It Works", result );
}
}

Handle class for jetty implementation
Private class testgetcontentokhandler extends acthttphandler
{
Public void handle (string pathincontext, string pathparams, httprequest request, httpresponse response) throws ioexception
{
Outputstream out = response. getoutputstream ();
Bytearrayiso8859writer writer = new bytearrayiso8859writer ();
Writer. Write ("It Works ");
Writer. Flush ();
Response. setintfield (httpfields. _ contentlength, writer. Size ());
Writer. writeto (out );
Out. Flush ();
Request. sethandled (true );
}

6. testsetup in testcase
Provides global setup and teardown for all testcase
Extend testsetup to provide global setup and teardown

For example, if all testcase needs to start jetty server in setup, this should not be done in every testcase.
By inheriting testsetup, the code for creating global resources is put in setup.

Import JUnit. Extensions. testsetup;
Public class testwebclientsetup1 extends testsetup
{
Protected static httpserver server;
Public testwebclientsetup1 (test suite)
{
Super (suite );
}
Protected void setup () throws exception {
... // The Code shocould be here
}
}

Configure testsetup
Public class testwebclient1 extends testcase
{
Public Static Test Suite ()
{
Testsuite suite = new testsuite ();
Suite. addtestsuite (testwebclient1.class );
Return new testwebclientsetup1 (suite );
}
...
}

Chapter 7 testing in isolation with mock objects
Mock object

1. Definition
Mock object-a mock object (or mock for short) is an object created
Stand in for an object that your code will be collaborating with. Your
Code can call methods on the mock object, which will deliver results
As set up by your tests.

2. Best practices
2.1 don't write business logic in mock objects
The opposite of stub, including logic.

2.2 only test what can possibly break

3. Adaptability
Real object has non-deterministic behavior
Real Object is difficult to set up
Real object has behavior that is hard to cause (such as a network error)
Real Object is slow
Real object has (or is) a UI
Mock object as a means of Reconstruction

4. Advantages
Mock object is simple (because it does not include Logic)
Mock object is an empty shell (empty shell) and does not need to be tested by itself.

5. Instance
5.1 classes to be tested
Public class WebClient
{
Public String getcontent (URL)
{
Stringbuffer content = new stringbuffer ();
Try
{
Httpurlconnection connection = (httpurlconnection) URL. openconnection ();
Connection. setdoinput (true );
Inputstream is = connection. getinputstream ();
Byte [] buffer = new byte [2048];
Int count;
While (-1! = (COUNT = is. Read (buffer )))
{
Content. append (new string (buffer, 0, count ));
}
}
Catch (ioexception E)
{
Return NULL;
}
Return content. tostring ();
}
}
If you want to use a mock object for testing, see the following:
Public void testgetcontentok () throws exception
{
Mockhttpurlconnection mockconnection = new mockhttpurlconnection ();
Mockconnection. setupgetinputstream (New bytearrayinputstream ("It Works". getbytes ()));
Mockurl = new mockurl ();
Mockurl. setupopenconnection (mockconnection );

WebClient client = new WebClient ();
String result = client. getcontent (mockurl );
Assertequals ("It Works", result );
}
It is difficult to generate a mock object because the URL is a final class and the mock object cannot be implemented by inheriting the URL.
Mock test helps refactoring to generate flexible code
The book provides two Reconstruction Methods
One method is to add an interface. The main test in the class is to retrieve the connection from the URL. Add a setconnection and getconnection method to allow external setup of connection (IOC). Use the getconnection method in the class to call the connection instance to obtain the mock class of the connection to test the connection.

Another method is to modify the original interface, change the getcontent parameter type from URL to a new factory type, define a new connection factory, and directly return the input stream. The Code is as follows:
Public interface connectionfactory
{
Inputstream getdata () throws exception;
}

Public String getcontent (connectionfactory)
{
...
Inputstream is = connectionfactory. getdata ();
...
}

However, mock is not suitable for third-party libraries that cannot be modified but are not well designed.

Chapter 8 in-container testing with cactus

Two methods for testing Servlet
Stub container: httpunit (http://httpunit.sourceforge.net /).

8.1 outside-the-container testing with mock objects for Servlet
8.1.1 Overview
Easymock is implemented using the dynamic proxy of JDK.
Http://www.easymock.org/

8.1.2 instance
Servlet code to be tested
Public class sampleservlet extends httpservlet
{
Public Boolean isauthenticated (httpservletrequest request)
{
Httpsession session = request. getsession (false );
If (session = NULL)
{
Return false;
}
String authenticationattribute = (string) Session. getattribute ("authenticated ");
Return Boolean. valueof (authenticationattribute). booleanvalue ();
}
}

Simulation code of easymock
Import org. easymock. mockcontrol;

Public class testsampleservlet extends testcase
{
Private sampleservlet;
Private mockcontrol controlhttpservlet;
Private httpservletrequest mockhttpservletrequest;
Private mockcontrol controlhttpsession;
Private httpsession mockhttpsession;

Protected void setup ()
{
Servlet = new sampleservlet ();
Controlhttpservlet = mockcontrol. createcontrol (httpservletrequest. Class );
Mockhttpservletrequest = (httpservletrequest) controlhttpservlet. getmock ();

Controlhttpsession = mockcontrol. createcontrol (httpsession. Class );
Mockhttpsession = (httpsession) controlhttpsession. getmock ();
}

Protected void teardown ()
{
Controlhttpservlet. Verify ();
Controlhttpsession. Verify ();
}

Public void testisauthenticatedauthenticated ()
{
Mockhttpservletrequest. getsession (false );
Controlhttpservlet. setreturnvalue (mockhttpsession );

Mockhttpsession. getattribute ("authenticated ");
Controlhttpsession. setreturnvalue ("true ");

Controlhttpservlet. Replay ();
Controlhttpsession. Replay ();
Asserttrue (servlet. isauthenticated (mockhttpservletrequest ));
}
}

8.1.3 disadvantages
A. Lack of Interaction tests with containers
B. deployment tests without component
C. Additional API knowledge (such as servlet) is required)
D.

8.2 In-container testing using cactus for sevelet.
8.2.1 tools
Cactus http://jakarta.apache.org/cactus/

8.2.2 Definition
A unit-testing framework specializing in Integration Unit-testing for server-side Java components.

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.