This site contains the documentation that is relevant to older WSO2 product versions and offerings.
For the latest WSO2 documentation, visit https://wso2.com/documentation/.

Writing a Test Case for BPS

This page explains how to write a simple BPS-BPEL integration test.

Note: You can start writing your tests in the following location according to your BPS server version:

bps/x.x.x/modules/integration/org.wso2.bps.bpel.taftests

E.g.:

/products/bps/x.x.x/modules/integration/org.wso2.bps.bpel.taftests)

Create a BPSMasterTest.java in which you can keep important common methods that you might call inside your test class. Refer the table below to see an example BPSMasterTest.java in a more common form (for illustration purposes only).

package org.wso2.carbon.bps;

import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException;
import org.wso2.carbon.automation.api.clients.authenticators.AuthenticatorClient;
import org.wso2.carbon.automation.api.clients.bpel.BpelUploaderClient;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.bpel.stub.mgt.PackageManagementException;
import javax.xml.xpath.XPathExpressionException;
import java.rmi.RemoteException;

public class BPSMasterTest {

    private static AutomationContext automationContext;
    protected BpelUploaderClient bpelUploaderClient;
    protected AuthenticatorClient authenticatorClient;

    protected void init() throws RemoteException, LoginAuthenticationExceptionException, 
                                 XPathExpressionException {
        init(0);
    }

    protected void init(int userID) throws RemoteException, LoginAuthenticationExceptionException, 
                                           XPathExpressionException {
        automationContext = new AutomationContext("BPS", true, true);
        bpelUploaderClient = new BpelUploaderClient(getBackendURL(), getSessionCookie());
        authenticatorClient = new AuthenticatorClient(getBackendURL());
    }

    protected String getBackendURL() throws XPathExpressionException {
        return automationContext.getContextUrls().getBackEndUrl();
    }

    protected String getSessionCookie() throws XPathExpressionException, LoginAuthenticationExceptionException, RemoteException {
        return automationContext.login();
    }

    protected String getServiceURL() throws XPathExpressionException {
        return automationContext.getContextUrls().getServiceUrl();
    }

    protected void uploadBpelForTest(String bpelName) throws RemoteException, InterruptedException, 
															 PackageManagementException {
        uploadBpelForTest(bpelName, "xxx/bps/3.x.x/modules/integration/org.wso2.bps.bpel.taftests/src/test/resources/artifacts/bpel");
    }

    protected void uploadBpelForTest(String bpelPackageName, String artifactLocation) throws RemoteException, InterruptedException, 
	                                                                                         PackageManagementException {
        bpelUploaderClient.deployBPEL(bpelPackageName, artifactLocation);
    }

 }
package org.wso2.carbon.bps;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.authenticator.stub.LoginAuthenticationExceptionException;
import org.wso2.carbon.authenticator.stub.LogoutAuthenticationExceptionException;
import org.wso2.carbon.automation.api.clients.bpel.BpelPackageManagementClient;
import org.wso2.carbon.bpel.stub.mgt.PackageManagementException;

import javax.xml.stream.XMLStreamException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

public class BPELBasicActivitiesTest extends BPSMasterTest {

    private static final Log log = LogFactory.getLog(BPELBasicActivitiesTest.class);

    BpelPackageManagementClient bpelPackageManagementClient;

     // 01
    public void setEnvironment() throws LoginAuthenticationExceptionException, RemoteException, XPathExpressionException {
        init();
        bpelPackageManagementClient = new BpelPackageManagementClient(getBackendURL(), getSessionCookie());
    }

    @BeforeClass(alwaysRun = true)
    public void deployArtifact() throws Exception {
        setEnvironment();
        uploadBpelForTest("TestIf");
        uploadBpelForTest("HelloWorld2");
        waitForProcessDeployment(getBackendURL() + "HelloService");
    }

    @AfterClass(alwaysRun = true)
    public void removeArtifacts() throws PackageManagementException, InterruptedException, RemoteException,
                                          LogoutAuthenticationExceptionException {
        bpelPackageManagementClient.undeployBPEL("HelloWorld2");
        bpelPackageManagementClient.undeployBPEL("TestIf");
        this.authenticatorClient.logOut();
    }

    // 03
    @Test(groups = {"wso2.bps", "wso2.bps.bpelactivities"}, description = "Hello World test case", priority = 0)
    public void helloWorld() throws InterruptedException, RemoteException, PackageManagementException, MalformedURLException, XMLStreamException, XPathExpressionException {
        String payLoad = " <p:hello xmlns:p=\"http://ode/bpel/unit-test.wsdl\">\n" +
                "      <!--Exactly 1 occurrence--><TestPart>test</TestPart>\n" +
                "   </p:hello>";

         String operation = "hello";
        String serviceName = "HelloService";
        String expectedBefore = "World";
        assertRequest(getBackendURL() + serviceName, operation, payLoad,
                1, expectedBefore, true);

     }

    @Test(groups = {"wso2.bps", "wso2.bps.bpelactivities"}, description = "if true test case")
    public void ifTrue() throws XMLStreamException, InterruptedException, AxisFault, XPathExpressionException {
        String payLoad = " <p:hello xmlns:p=\"http://ode/bpel/unit-test.wsdl\">\n" +
                "      <!--Exactly 1 occurrence-->\n" +
                "      <TestPart>2.00</TestPart>\n" +
                "   </p:hello>";

         String operation = "hello";
        String serviceName = "TestIf";
        String expectedBefore = "Worked";
        assertRequest(getBackendURL() + serviceName, operation, payLoad,
                1, expectedBefore, true);
    }

    @Test(groups = {"wso2.bps", "wso2.bps.bpelactivities"}, description = "if false test case")
    public void ifFalse() throws XMLStreamException, InterruptedException, AxisFault, XPathExpressionException {
        String payLoad = " <p:hello xmlns:p=\"http://ode/bpel/unit-test.wsdl\">\n" +
                "      <!--Exactly 1 occurrence-->\n" +
                "      <TestPart>1.00</TestPart>\n" +
                "   </p:hello>";

         String operation = "hello";
        String serviceName = "TestIf";
        String expectedBefore = "Failed";
        assertRequest(getBackendURL() + serviceName, operation, payLoad,
                1, expectedBefore, true);
    }

    // 02
    private void waitForProcessDeployment(String serviceUrl) throws Exception {
        int serviceTimeOut = 0;
        while (!this.isServiceAvailable(serviceUrl)) {
            if (serviceTimeOut == 0) {
                log.info("Waiting for the " + serviceUrl + ".");
            } else if (serviceTimeOut > 200) {
                log.error("Time out");
                throw new Exception(serviceUrl + " service is not found");
            }
            try {
                Thread.sleep(500);
                serviceTimeOut++;
            } catch (InterruptedException ignored) {
            }
        }
    }

 
    private boolean isServiceAvailable(String serviceUrl) {
        URL wsdlURL;
        InputStream wsdlIS;
        try {
            wsdlURL = new URL(serviceUrl + "?wsdl");
        } catch (MalformedURLException e) {
            return false;
        }
        try {
            wsdlIS = wsdlURL.openStream();
        } catch (IOException e) {
            return false;// do nothing, wait for the service
        }

         if (wsdlIS != null) {
            byte[] bLine = new byte[1024];
            int read;
            try {
                read = wsdlIS.read(bLine);
            } catch (IOException e) {
                return false;
            }

             if (read > 0) {
                String wsdl = new String(bLine);
                if (wsdl.contains("definitions")) {
                    return true;
                }
            }
            return false;
        }
        return false;
    }

    // 04
    private void assertRequest(String eprUrl, String operation, String payload,
                               int numberOfInstances, String expectedException, boolean twoWay)
            throws XMLStreamException, AxisFault {

 
         for (int i = 0; i < numberOfInstances; i++) {
            OMElement result = null;
            try {
                EndpointReference epr = new EndpointReference(eprUrl + "/" + operation);
                if (twoWay) {
                    result = this.sendRequest(payload, epr);
                    //  Assert.fail("Exception expected!!! : " + result.toString());

                 } else {
                    this.sendRequestOneWay(payload, epr);
                }
            } catch (XMLStreamException e) {
                if (!e.getClass().getSimpleName().equals(expectedException)) {
                    throw new XMLStreamException(e);
                }
            } catch (AxisFault axisFault) {
                axisFault.printStackTrace();
                if (!axisFault.getClass().getSimpleName().equals(expectedException)) {
                    throw new AxisFault(axisFault.getMessage());
                }
            }

             assert result != null;
            if (!(result.toString().contains(expectedException))) {
                Assert.fail("Expected response not found");
            }
        }
    }

    // 05
    private static OMElement sendRequest(String payloadStr, EndpointReference targetEPR)
            throws XMLStreamException, AxisFault {

         OMElement payload = AXIOMUtil.stringToOM(payloadStr);
        Options options = new Options();
        options.setTo(targetEPR);
        ServiceClient sender = new ServiceClient();
        sender.setOptions(options);
        log.info("Request: " + payload.toString());
        OMElement result = sender.sendReceive(payload);
        log.info("Response: " + result.toString());
        return result;
    }

    // 06
    public void sendRequestOneWay(String payloadStr, EndpointReference targetEPR)
            throws XMLStreamException, AxisFault {
        OMElement payload = AXIOMUtil.stringToOM(payloadStr);
        Options options = new Options();
        options.setTo(targetEPR);
        ServiceClient sender = new ServiceClient();
        sender.setOptions(options);
        log.info("Request: " + payload.toString());
        sender.fireAndForget(payload);
    }
}

Prerequisites: 

The TestIf.zip and HelloWorld2.zip artifacts must be placed inside the bpel package in ../xxx/bps/3.x.x//x.x.x/modules/integration/org.wso2.bps.bpel.taftests/src/test/resources/artifacts.  

Description:

  1. setEnvironment method

    Defined under the BeforeClass annotation. This will set up the environment required to run your test. It will create the following four objects:
    1. automationContext - TAF will allow you to create an AutomationContext object in accordance with the provided parameters given at the initial stage of the test. It is more of a custom runtime environment that suits running your tests.
    2. bpelUploaderClient - uploads/deploy bpel to the server.
    3. authenticatorClient - handles the logout operation.
    4. bpelPackageManagementClient - undeploys bpels.
  2. waitForProcessDeployment method

    This method will ensure that the uploaded bpel artifacts are deployed as expected. It uses threading for this operation.
  3. helloWorld method

    This operation invokes the HelloWorld service (fo HelloWorld2) uploaded. 
  4. assertRequest method

    Sends requests and asserts the response. 
  5. sendRequest method

    Sends the request to the server. You need to pass the payload string together with the endpoint reference to the method body and it will send the request the service endpoint and return the response received.
  6. sendRequestOneWay method

    Differs from the sendRequest method by not expecting any response to the request.
  7. removeArtifacts method

    Defined under the AfterClass annotation, carries on the operations for the removal of artifacts uploaded and the log-out operation.