Chapter II Exploring Junit1.junit Testcase TestSuite - Designed To Run One or More Test CasesteStrunner - Launches The Testsuite
2. Composite Pattern applies TestSuite and TestCase in JUnit to implement Test interface, add TEST objects in TestSuite, which means you can add TestSuite to run a set of Test, 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 (TestDefaultController.class); // if TestDefaultController had a Suite Method // (or Alternate Suite Methods) You Could Also Use // Suite.addtestsuite (TestDefaultController.suite ()); Return Suite;}}
3. FAILURES AND ERRORSJUNIT distinguishes Failures and Errors.Failures are expected to be expected to change the failure caused by code. Error is an error that cannot be expected, such as a network connection failed. Chapter 4 Examining Software Tests software testing several categories: 1.Unit Test2.integration Test Integration Test 3.Feature Test Features Test USE Case4.stress / Load TEST Pressure Test 5.acceptance Test Acceptance Tools STRESS / LOAD TEST Tools JMeter http://jakarta.apache.org/jmeterjunitPerf Code coverage Test Clover http://www.thecortex.net/clover/ jesterquestion: No integration test Can you do a function test before? The company's Software Process is a functional test for Component, and then integrates the test. Chapter 5 Automating Junit
JUnit Ant
There is already a continuous test frame CruiseControlhttp: //blog.9cbs.net/chelsea/archive/2004/11/22/190545.aspx Chapter 6 COARSE-GRAINED TESTING WITH Stubs Objects1. Define Runtime Dynamic Insert for Alternatives The object of the real environment.
Stub-a stub is a portion of code That ISITED AT Runtime in place of the real code, in Order to isolate calling code from the real importation.2. Applicability Coarse granularity 3. Writing, debugging, maintenance is too complex 4. Embedded Server embedded by the tool Jetty (Stubbing the Web Server's Resources), by inheriting its ResourceHandler class, analog web server response. Http: //jetty.mortbay.org/jetty/index.html launches Jettyhtpserver server = new HttpServer (); SocketListener listener = new SocketListener (); listener.setPort (8080); // bind to the listener port 8080, receiving the HTTP requestserver.addListener (listener); HttpContext context = new HttpContext (); context .setContextPath ("/"); context.SetResourceBase ("./"); context.addhandler (new resourcehandler ()); server.addContext (context); server.Start (); 5. Example TestCase code 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.SETCONTEXT Path ( "/ 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);}} is achieved Jetty handle class private class TestGetContentOkHandler extends AbstractHttpHandler {public void handle (String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws OutputStream out = response.getOutputStream IOException {();
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 TeardowNextend TestSetup to Provide Global Setup and Teardup to Provide Global Setup and TeardUp To PROVIDE GLOBAL SETUP AND TEARDOWN, all TestCase needs to start Jetty Server in Setup, shouldn't Do this in each TestCase. By inheriting TestSetup, place the code of the global creating resources 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 should be here} configuration} TestSetuppublic class TestWebClient1 extends TestCase {public static Test suite () {TestSuite suite = new TestSuite (); suite.addTestSuite (TestWebClient1.class); return new TestWebClientSetup1 (suite);} ...} Chapter VII Testing in isolation with mock objectsmock object1. definitions mock object-A mock object (or mock for short) is an object created tostand in for an object that your code will be collaborating with. yourcode can call methods on the mock object, which will deliver resultsas set up BETS.2. Best Practices 2.1 Don't Write Business Logic in Mock ObjectSstub is opposite, containing logic.
2.2 Only test what can possibly break3. 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 UIMOCK Object as a means of reconstruction 4. Advantages Mock Object is simple (because logic) Mock Object is an empty shell, it does not need to test 5. Example 5.1 Required class public classes WebClient {public String getContent (URL 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 wish to use mock test object, as follows: public void testGetContentOk () throws Exception {MockHttpURLConnection mockConnection = new MockHttpURLConnection (); mockConnection.setupGetInputStream (new ByteArrayInputStream ( "IT Works" .getbytes ())); M ockURL mockURL = new MockURL (); mockURL.setupOpenConnection (mockConnection); WebClient client = new WebClient (); String result = client.getContent (mockURL); assertEquals ( "It works", result);} In this way it does not work, it is It is difficult to generate a MOCK object because the URL is a final class, which cannot achieve the MOCK object Mock Test help reconstruction. It provides two reconstruction methods in the flexible code book to increase the interface, the main test in the class. Is the connection taken from the URL. Increase a SETCONNECTION and GetConnection method, allowing external settings Connection (IOC), and use the getConnection method to call the Connection's MOCK class to test the Connection Mock class. Another way is to modify the original interface, change the parameter type of GetContent to the introduction of a new factory type, define a new connection plant, and return to the input stream.
The following code public interface ConnectionFactory {InputStream getData () throws Exception;} public String getContent (ConnectionFactory connectionFactory) {... InputStream is = connectionFactory.getData (); ...} but if you want the library to a third party, can not be modified, And there is no good design, then Mock is not very suitable. Chapter VIII In-container testing with two ways of Cactus test Servlet Stub container: HttpUnit (http://httpunit.sourceforge.net/).8.1 Outside-the-container testing with mock objects for Servlet8.1.1 outlined with JDK EasyMock Dynamic Proxy implementation http://www.easymock.org/
8.1.2 Examples of the code to be tested Servlet public class SampleServlet extends HttpServlet {public boolean isAuthenticated (HttpServletRequest request) {HttpSession session = request.getSession (false); if (session == null) {return false;} String authenticationAttribute = (String Session.getaTribute ("Authenticated"); return boolean.valueof (AuthenticationAttribute) .BooleanValue ();}}
Easymock's simulation code import org.easymock.mockcontrol;
public class TestSampleServlet extends TestCase {private SampleServlet servlet; 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); mockhtpsession = (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 with the container B. Lack of deployment tests for Component C. Require additional API knowledge (such as servlet) D.
8.2 in-Container Testing Using Cactus for Sevelet.8.2.1 Tool Cactus http://jakarta.apache.org/cactus/
8.2.2 Defining a Unit-Testing Framework Specializing In Integration Unit-Testing for Server-Side Java Components.