Unit Testing Web Services
by Paul Hamill

Listing One

public class MyServiceTest extends TestCase {
    public void setUp() {
        String URI = "http://localhost:8080/services/MyService";
        // ... create service endpoint and connect to URI ...
        MyService service = endpoint.getMyService();
    }
    public void testGetDoc() {
        service.putDoc( "test" );
        assertEquals( "test", service.getDoc() );
    }
    public void tearDown() {
        service.destroy();
    }
}


Listing Two

<?xml version="1.0" encoding="UTF-8"?>
<definitions name="MyService"
    targetNamespace="http://services.corp.com/namespaces/MyService">
<!-- ... -->
        <!-- getImage -->
        <xsd:element name="getImageRequest" type="xsd:string"/>
        <xsd:element name="getImageResponse">
            <xsd:complexType>
               <xsd:sequence>
                  <xsd:element name="data" type="xsd:base64Binary"/>
               </xsd:sequence>
            </xsd:complexType>
        </xsd:element>
<!-- ... -->
</definitions>


Listing Three
public class MyServiceTest extends TestCase {
    public void testGetImage() {
        GetImageResponse r = service.getImage( "test.image.1" );
        assertEquals( 72000, r.getData().length );
    }
}


Listing Four

public class MyServiceTest extends TestCase {
    public void testInvalidLogin() {
        try {
            service.login( "not_a_real_login", "bad_password" );
                fail( "Expected LoginException not thrown" );
        } catch ( LoginException e ) {} // expected exception
    }
}


Listing Five

public class MyServiceTest extends TestCase {
    public void testTimeout() {
        service.setTimeout( Calendar.SECOND, 1 );
        try {
            Thread.sleep(1010); // wait for timeout
        } catch (InterruptedException e) {}
        try {
            service.putDoc( "test" ); // try to call service
                fail( "Expected RemoteException not thrown" );
        } catch ( RemoteException e ) {} // expected exception
    }
}


Listing Six

public class MyServiceTest extends TestCase {
    public void testMultipleConnections() {
        MyService service1 = endpoint.getMyService();
        MyService service2 = endpoint.getMyService();
        service1.putDoc( "test" );
        assertFalse( "test" == service2.getDoc() );
    }
}

Listing Seven

public class MyServiceTest extends TestCase {
    public void testGetDocTime() {
        long startTime = System.currentTimeMillis();
        String doc = service.getDoc();
        long endTime = System.currentTimeMillis();
        assertTrue( endTime-startTime < 100 );
    }
}


Listing Eight

public class MyServiceTest extends TestCase {
    public void testLargeDoc() {
        StringBuffer doc = new StringBuffer(1000000); // 1 MB string
        for (int i = 0; i<1000000; i++) doc.append("X");
        service.putDoc( doc.toString() );
        String d = service.getDoc();
        assertEquals( doc.toString(), d );
    }
}





2


