You are browsing the archive for Java.

Dagger 2, MVP and Unit Testing (PIT Mutation Testing) – Part 4

September 25, 2016 in Android, Java, Unit Testing

The previous three articles[1] showed an introduction to Dagger, MVP pattern, Espresso and more. This article focuses on introducing a powerful test coverage technique for ensuring that the app unit tests are strong enough.

Introduction to Mutation Testing

One of the golden standard test coverage techniques is mutation testing. The main idea of mutation testing is to perform byte code modifications (mutations) to your original app source code and then run your app unit tests to check if they are strong enough to fail as a result of these mutations.

The byte code changes in Mutation Testing are named as faults (or mutations). After applying the source code changes, if your tests fail then the mutation is killed, and if your tests pass then the mutation is lived.

So in summary, If your tests fail by source code mutations then this means that your tests are really strong, if your tests pass then this means you need to modify your tests to make them strong enough (The quality of your tests can be gauged from the percentage of mutations killed).

Why we need Mutation Testing

Mutation tests have an advantage over Traditional test coverage (i.e line, statement, branch etc) because it does not only measure which code is executed by your tests but also it checks that your tests are actually able to detect faults in the executed code. This gives a strong measurement to your developed unit tests.

PIT

PIT is one of the mutation testing systems for Java. It has several advantages:

  1. Fast to execute.
  2. Integrated with Java build tools (Ant, Maven and Gradle).
  3. Active.

More information about PIT can be found in:
http://pitest.org/

Android Integration

Unfortunately, the official PIT Gradle plugin does not work fine with Android Gradle projects:
https://github.com/szpak/gradle-pitest-plugin

However, thanks to one of the community member, this support is now possible using this fork:
https://github.com/koral–/gradle-pitest-plugin

Application Configuration

In order to configure Android PIT plugin with our Android Dagger app:
1. Add PIT plugin to your top-level build.gradle file:

classpath 'pl.droidsonroids.gradle:gradle-pitest-plugin:0.0.3'

2. Configure PIT plugin in your app build.gradle file:

pitest {
   targetClasses = ['com.test.xyz.daggersample1.ui.presenter.*']  /* specify target classes to be mutated */
   excludedClasses = ['**Factory*'] /* Exclude Dagger generated classes */
   pitestVersion = "1.1.0" 
   threads = 4 /* specify number of threads */
   outputFormats = ['XML', 'HTML'] /* specify output format */
}

Checking Results

After configuration, finally, we can execute PIT tests by running:

./gradlew pitest

You can pick the PIT tests report under build/reports/pitest.

The following figure shows the mutation testing report in our Dagger sample:
PIT Report

The following figure shows survived and killed mutants:
Mutants

FYI, in the mutation report, Light green shows line coverage, dark green shows mutation coverage, Light pink show lack of line coverage, and dark pink shows lack of mutation coverage.

Source code

App Source code is available in:
https://github.com/hazems/Dagger-Sample/tree/pit1/app/src/test/java/com/test/xyz/daggersample1/ui/presenter

Top-level Gradle file PIT configuration:
https://github.com/hazems/Dagger-Sample/blob/pit1/build.gradle

Module-level Gradle file PIT configuration:
https://github.com/hazems/Dagger-Sample/blob/pit1/app/build.gradle

In our next article, let’s see how to kill these survived mutants which makes our tests not strong enough!

[1] Previous articles:
http://www.technicaladvices.com/2016/03/05/an-introduction-to-dagger-2-android-di-part-1/
http://www.technicaladvices.com/2016/03/09/an-introduction-to-dagger-2-android-di-part-2/
http://www.technicaladvices.com/2016/04/07/dagger-2-mvp-and-unit-testing-android-di-part-3/

The effective Java logout servlet code

July 8, 2012 in Java, Java Web

What is the issue?

You may face an issue when you try to write your own Servlet logout code as follows:

protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {

	request.getSession().invalidate();
	response.sendRedirect(request.getContextPath() + "/login.jsp");
}

The issue in this code is that after it runs on the web container, You may find that the user session is not cleared completely in IE (However, on Safari, Chrome, and Firefox, it may work fine). i.e) You can access pages that requires a user authentication after running this logout code in IE.

Why do we have this issue?

Well, this issue is related to the caching of the pages in the Internet Explorer.

How to solve this issue?

You need to prevent the page caching from the HTTP response as follows:

protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {

	response.setHeader("Cache-Control", "no-cache, no-store");
	response.setHeader("Pragma", "no-cache");

	request.getSession().invalidate();
	response.sendRedirect(request.getContextPath() + "/login.jsp");
}

After writing the first two headers response lines, your logout will work in all the browsers.

java.net.SocketTimeoutException: Socket operation timed out before it could be completed

June 19, 2012 in General, Java

You may face this exception in the log file of your web application:

java.net.SocketTimeoutException: Socket operation timed out before it could be completed

After investigating in the error, I found that it happens because of the network connectivity. I could fix it by fixing the network cable.

Five Steps to use Apache Cactus with WebSphere Application Server 7

April 13, 2012 in Java, Unit Testing, WebSphere

This post illustrates setting up the Apache Cactus on WebSphere 7.0 to test some JPA managers in an existing web application.

Let’s go through the steps, so you can do them directly in maximum 5 minutes:

1. Download the Apache Cactus 1.8.0.zip from here.

2. Place ONLY the following jars in the lib folder of your web application:

    2.1. aspectjrt-1.5.3.jar
    2.2. cactus.core.framework.uberjar.javaEE.14-1.8.0.jar
    2.3. cactus.integration.ant-1.8.0.jar
    2.4. cactus.integration.shared.api-1.8.0.jar
    2.5. cargo-ant-0.9.jar
    2.6. cargo-core-uberjar-0.9.jar
    2.7. commons-codec-1.3.jar
    2.8. commons-httpclient-3.1.jar
    2.9. commons-logging-1.1.jar
    2.10. httpunit-1.6.jar
    2.11. js-14.jar (You will have to download this file manually to avoid OutOfMemory Exception on WebSphere).
    2.12. junit-3.8.2.jar
    2.13. nekohtml-1.9.6.jar
    2.14. org.mortbay.jetty-5.1.9.jar
    2.15. xbean-1.0.3.jar (You will have to download this file manually to avoid OutOfMemory Exception on WebSphere).

3. Copy the following servlets declaration to your web.xml file:

<!-- [Start] Cactus Configuration -->
	<servlet>
	  <servlet-name>ServletRedirector</servlet-name>
	  <servlet-class>org.apache.cactus.server.ServletTestRedirector</servlet-class>
	</servlet>
	<servlet>
	  <servlet-name>ServletTestRunner</servlet-name>
	  <servlet-class>org.apache.cactus.server.runner.ServletTestRunner</servlet-class>
	</servlet>
	<servlet-mapping>
	    <servlet-name>ServletRedirector</servlet-name>
	    <url-pattern>/ServletRedirector</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
	    <servlet-name>ServletTestRunner</servlet-name>
	    <url-pattern>/ServletTestRunner</url-pattern>
	</servlet-mapping>
<!-- [End] Cactus Configuration -->

4. Write your web test cases.

public class TestServlet extends ServletTestCase {
    public void testCreatePerson() {
        try {
            FacesContext  facesContext  = JSFUtil.getFacesContext(config.getServletContext(), request, response);
            PersonManager personManager = (PersonManager) JSFUtil.getManagedBean(facesContext, "personManager");            
            Person person = new Person();
            person.setPersonName("Hazem" + System.currentTimeMillis());
            person.setPersonNationalId(System.currentTimeMillis() + "");
            personManager.createPerson(person);
        } catch (Exception exception) {
            exception.printStackTrace();
            fail(exception.getMessage());
        }
    } 
    // Other test cases ...
}

As you notice, Cactus is much similiar to JUnit, Your web testcases class should just extend the (org.apache.cactus.ServletTestCase).

5. Finally, deploy the web application war to the WAS 7.0, and access your web testcases class through the (ServletTestRunner) by using the following URL:
http://localhost:9080/testWebProject/ServletTestRunner?suite=entities.controller.test.TestServlet.

As you see here, you just set the suite parameter to the fully-qualified name of your web testcases class.

Here is the sample output:

If you want a nicer output, then make sure to include the cactus-report.xsl [This file is included in the sample] directly under the (Web Content) folder of your application, and add the xsl parameter as follows:
http://localhost:9082/testWebProject/ServletTestRunner?suite=entities.controller.test.TestServlet&xsl=cactus-report.xsl.

Here is the cooler output:

I included all of the project source code including the dependency jars in the following zip file for your reference. I wish that this tip can be helpful to you.

Java getting the class path in the runtime

March 26, 2012 in Java

In some cases, you may need to know for debugging purposes from where a specific class is loaded. This happens usually if there are two different versions of the class in the class path (the one used in compilation is different from the one used in the runtime) which results in the popular java.lang.NoClassDefFoundError error).

Thanks to the ProtectionDomain, you can get this information as shown below.

try {
	Class myclass = Class.forName("org.apache.commons.logging.Log"); /*or any other class you wish*/
	System.out.println(myclass.getProtectionDomain().getCodeSource()
			.getLocation());

} catch (ClassNotFoundException e) {
	e.printStackTrace();
}

Java Converting String to InputStream

March 11, 2012 in Java

This is the short tip of the day, this tip can be helpful to you if you are wishing, for example, to parse an XML String using the Java DOM APIs or in general if you are working with an API that does not expose an interface to accept the content as a String and it exposes an interface that accepts an input stream.

Using the java.io.ByteArrayInputStream class you can convert a String object to a byte array input stream as follows:

InputStream istream = new ByteArrayInputStream(xmlString.getBytes("UTF-8"));
Profile photo of hazems

by hazems

Ajax file upload to a Java Servlet in HTML5

December 10, 2011 in HTML5, Java, JavaScript

HTML5 comes with a great feature which is the ability to upload files using the XMLHttpRequest version 2.
Modern Gecko and WebKit browsers include a wonderful object FormData that allows combining both simple and complex form data (text and files) in the Ajax request object.

Let's show you how to do this.

In the example, we are having a form with two fields, one field represents a simple text field, and the other one represents a file field as shown in the code below.

<form id="form1">    

    <label for="sampleText">Please enter a text</label>

    <input id="sampleText" name="sampleText" type="text" /> <br/>

    <label for="sampleFile">Please select a file

    <input id="sampleFile" name="sampleFile" type="file" /> <br/>

    <input id="uploadBtn" type="button" value="Ajax Submit" onClick="performAjaxSubmit();"></input>

</form>

<script type="text/javascript">

    function performAjaxSubmit() {

        var sampleText = document.getElementById("sampleText").value;

        var sampleFile = document.getElementById("sampleFile").files[0];

        var formdata = new FormData();

        formdata.append("sampleText", sampleText);

        formdata.append("sampleFile", sampleFile);

        var xhr = new XMLHttpRequest();       

        xhr.open("POST","/fileUploadTester/FileUploader", true);

        xhr.send(formdata);

        xhr.onload = function(e) {

            if (this.status == 200) {

               alert(this.responseText);

            }

        };                    

    }   

</script>

As we see in the listed code, it is a normal old XHR code, but it has two differences:
1. The files property in the HTML5 input file, which gives you the ability to get the file(s) object(s).
2. The FormData object, which has one method called append, that allows adding any form data (text and file) to the object. The FormData object has another big advantage which is making the Ajax request “multipart/form-data” without writting any special code.

Now, Let's move to the Servlet code (Iam using Apache Commons File Upload for handling the multipart form request parsing).

public class FileUploader extends HttpServlet {

    protected void doPost(HttpServletRequest request,

                          HttpServletResponse response)

                          throws ServletException, IOException {

        String ajaxUpdateResult = "";

        try {

            List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);            

            for (FileItem item : items) {

                if (item.isFormField()) {

                    ajaxUpdateResult += "Field " + item.getFieldName() + 

                    " with value: " + item.getString() + " is successfully read\n\r";

                } else {

                    String fileName = item.getName();

                    InputStream content = item.getInputStream();

                    response.setContentType("text/plain");

                    response.setCharacterEncoding("UTF-8");

                    // Do whatever with the content InputStream.

                    System.out.println(Streams.asString(content));

                    ajaxUpdateResult += "File " + fileName + " is successfully uploaded\n\r";

                }

            }

        } catch (FileUploadException e) {

            throw new ServletException("Parsing file upload failed.", e);

        }

        response.getWriter().print(ajaxUpdateResult);

    }
}

The Servlet simply parses the multipart form request and then constructs a message with the result.

Please keep in mind that this code will work with Chrome 5 and Safari 5, Firefox 4 but unfortunately will not work with IE9 because miserably IE9 does not have the FormData object, I will show later how you can achieve the same behaviour in IE9 “Iam sure you will not like it because it is much harder ;-)”.

Download the complete code from here.

Profile photo of hazems

by hazems

Efficient JavaScript unit testing

September 27, 2011 in Java, JavaScript, Web 2.0

I published this article in developerWork:
http://www.ibm.com/developerworks/library/os-jstesting/.

I wish it can be useful for you.

Profile photo of hazems

by hazems

Creating your Custom iWidget on the Process Server Business Space

August 18, 2011 in BPM, Java, WebSphere

I published the post content here: https://www.ibm.com/developerworks/mydeveloperworks/blogs/hazem/entry/creating_your_custom_iwidget_on_the_process_server_business_space1?lang=en.

Profile photo of hazems

by hazems

IE Redirection Problem inside Facebook Application's Canvas (IFrame) and Solution

December 27, 2010 in Java, Web 2.0

When working in my Facebook java application that performs Facebook authentication through OAuth. I found a very weird behavior when configuring my application on Facebook and setting the application canvas type to “IFrame”.

My FacebookSignInServlet is just redirecting the user to the Facebook graph OAuth authorization URL[1] and appending the application callback servlet URL to the Facebook graph OAuth authorization URL. This scenario works fine on all the browsers except IE.

After digging in the problem, I found that the problem was due to an IE iframe redirection security issue.

How to resolve this issue?

In your FacebookSignInServlet, set the P3P header to “IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT” as follows:

response.addHeader("P3P",
"CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");

And redirection will work without extra efforts from your side.

[1] https://graph.facebook.com/oauth/authorize

Skip to toolbar