JUnit Test Case Example for Web Application
In this tutorial, we shall show users the usage of JUnit Example Web Application. We will see how we can test our web applications and what are the technologies that we need to work with.
Table Of Contents
1. Introduction
We have seen various examples of testing our applications with JUnit. If you are already a regular reader of my JUnit tutorials, then you are already know that how JUnit eases life of a Java developer.
In this example we will try to find a solution of testing our web applications with the help of JUnit.
2. Technology Stack
In this example we will e using following technology stack:
- Java 1.8– We will be using the Java 1.8 for this example to work.
- JUnit 4.12– Testing framework
- Maven– Build and dependency tool. You can visit here for more details
- JWebUnit– Framework used with JUnit to test the web application. We will go into details in our example below.
- Eclipse – IDE for coding
3. What is JUnit?
There are several technologies out there which are used to test the applications. JUnit is one of them. It is very famous framework which is used by the Java developers for unit testing their applications. It provides lots of flexibility to test the application from a developers point of view.
You can get a detail tutorials about JUnit written by me here. Also you can follow the link to get all Junit related tutorials on Java Code Geeks.
Currently, latest stable version of JUnit is 4.x and 5.x is coming most probably in Q1 of 2017. JUnit contains many annotations that are used while creating test cases.
- @BeforeClass: It is used to write code that we want to run before all test cases.
- @Before: It will run before every test case.
- @Test: This is actual test case.
- @After: It will run after every test case.
- @AfterClass: It is used to write code that we want to run after all test cases.
For the sake of simplicity of the example, we are using the Maven so that you don’t need to include the jar yourself. Maven is dependency management tool for Java. The jar and its dependencies would be automatically pulled by Maven.
I would recommend readers to read the Mastering Unit Testing Using Mockito and JUnit and JUnit in Action for the deeper knowledge about the JUnit.
4. Ways to test Web Applications
Since in last all tutorials I have written, I had used the core java applications to test with JUnit. But we can also test the web applications with the help of JUnit. There are numerous frameworks available which in collaboration with JUnit helps in testing. You can use any one of them to test your web applications. Some of them are:
But in this example we will stick to the JWebUnit.
5. JWebUnit Introduction
JWebUnit is a Java based testing framework for web applications. JWebUnit provides a high-level Java API for navigating a web application combined with a set of assertions to verify the application’s correctness. This includes navigation via links, form entry and submission, validation of table contents, and other typical business web application features.
Here is the architecture of JWebUnit.
It wraps existing testing frameworks such as HtmlUnit and Selenium with a unified, simple testing interface to allow you to quickly test the correctness of your web applications.
You can read Selenium Web Driver Practical Guide about the usage of selenium web drivers to use for testing.
6. Project Setup
You may skip project creation and jump directly to the beginning of the example below.
Open Eclipse. File -> New -> Maven Project. First Screen will open. Go with defaults and click on Next button.
On this screen select maven-archetype-webapp from options and click on Next button.
On this final screen, fill in the details as shown and click on the Finish button.
Here we are ready with the blank maven web project. But before starting code, you need to create a folder under src/main and name it java. By default maven creates a src/main/resorces folder.
6.1 JWebUnit Installation
To continue using our example for testing web application we need to add the JUnitWeb jar file to out classpath. This can be achieved either by deploying directly the jar file or using the Maven.
Since we are using Maven for our example we will be using the pom.xml
for the dependency of the JUnitWeb jar.
Copy the below code and paste it onto the pom.xml file under the dependences
tag.
pom.xml
<dependency> <groupId>net.sourceforge.jwebunit</groupId> <artifactId>jwebunit-htmlunit-plugin</artifactId> <version>3.3</version> <scope>test</scope> </dependency>
7. JUnit Example Web Application
Here is the final structure of our example.
Let’s start by adding some code to the pom.xml
file.
pom.xml
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties>
Now we are ready to go with the coding of our example. But before starting the coding first we need to update the project so that it will use Java 8 for compilation and running. Simply right click on the project name -> Maven -> Update Project
On next screen simply click OK and maven will automatically update project.
Now our project is ready for testing.
7.1 JSP Pages
We will start by creating 2 JSP pages that we will test later on. Nothing is special in those. Both pages will contains the link to open the pages.
index.jsp
<html> <head> <title>Login</title> </head> <body> <a href="home.jsp" id="home">Go To Home</a> </body> </html>
The main thing about the above code is the line no 3 and 6. Here at line 6, we have put a link with id “home”. This is how actually out testing API will recognize it. This simple link will take us to the main page. Same will happen with line 3 where we will test the page title.
home.jsp
<html> <head> <title>Home</title> </head> <body> <h2>Welcome Home!</h2> <a href="index.jsp" id="login">Go To Login Page</a> </body> </html>
Same thing about the above code is the line no 3 and 7. Here at line 7, we have put a link with id “login”. This is how actually out testing API will recognize it. This simple link will take us to the login page. Same will happen with line 3, where we will test for the title of the page.
In our example, we basically will two test cases.
- Test login page
- Test main page
7.2 Java Test Class
Now we will create a JUnit Test class with the help of JWebUnit. Do not bother about code right now. We will explain it in details in next section. You simply grasp and try to think about it.
JWebUnitTest.java
package junitwebapp; import static net.sourceforge.jwebunit.junit.JWebUnit.assertLinkPresent; import static net.sourceforge.jwebunit.junit.JWebUnit.assertTitleEquals; import static net.sourceforge.jwebunit.junit.JWebUnit.beginAt; import static net.sourceforge.jwebunit.junit.JWebUnit.clickLink; import static net.sourceforge.jwebunit.junit.JWebUnit.setBaseUrl; import static net.sourceforge.jwebunit.junit.JWebUnit.setTestingEngineKey; import org.junit.Before; import org.junit.Test; import net.sourceforge.jwebunit.util.TestingEngineRegistry; public class JWebUnitTest { @Before public void prepare() { setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT); setBaseUrl("http://localhost:8081/junitwebapp"); } @Test public void testLoginPage() { beginAt("index.jsp"); assertTitleEquals("Login"); assertLinkPresent("home"); clickLink("home"); assertTitleEquals("Home"); } @Test public void testHomePage() { beginAt("home.jsp"); assertTitleEquals("Home"); assertLinkPresent("login"); clickLink("login"); assertTitleEquals("Login"); } }
We will examine each and every details of this class. Below line will sets the Engine for testing of our example.
setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT);
There are 2 engines that we can use. HTMLUNIT that we are using in our case or the WEBDRIVER.
Below line is the main where we are defining the URL of our testing application.
setBaseUrl("http://localhost:8081/junitwebapp");
As you can notice we are using the above statements in the @Before
test case, so that they will run before @Test
cases.
Next, we will explain the below Test method.
@Test public void testLoginPage() { beginAt("index.jsp"); assertTitleEquals("Login"); assertLinkPresent("home"); clickLink("home"); assertTitleEquals("Home"); }
Line no 3, will mark out beginning page to test. This will check the title of the page. As we have mentioned in section JSP Pages, we will here test the title of the page. If it matches then test case will pass otherwise it will fail.
assertTitleEquals("Login");
This will check that the link with the id is present. In our case home
is the id of the link.
assertLinkPresent("home");
Here clickLink("home");
will click on the link with the id “home”.
clickLink("home");
Here we are checking the title of the new page that is opened after cicking on the link. It should be Home. Otherwisw our test case will fail.
assertTitleEquals("Home");
JWebUnit has a vast API for testing defined elements of the web. You can visit javadocs for it.
Before running the Test class, you need to first deploy your application on any server. We are using the Apache Tomcat. If we miss this step then we will get the below error.
... Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source) ...
So, deploy your application on tomcat or any other web server. Once it is successfully deployed, we can proceed with the running of the test class.
Finally to run the class simply right click on the test class and Run As -> JUnit Test. Here is the final output in the Eclipse JUnit window.
8. Conclusion
Here in JUnit Example Web Application we have learned a simple testing of a web application. We have analyzed the code and seen that we need the JWebUnit for this type of testing where we need to test the web application. JWebUnit uses the HTMLUNIT or WEBDRIVER as the testing engine to test the web application.
You can assert any type of web element, may be a Form, Link, button or a table. For the simplicity perspective, we have only taken an example of the link element of the web. All other scenarios will work as same.
So, now you are ready to test the web applications with the help of JWebUnit.
9. Download the Eclipse Project
This is an example of JUnit Example Web Application with JWebUnit
You can download the full source code of this example here: junitwebapp.zip
Nice article. I’ve 1 question.. Can JWebUnit test spring webapp?
I am trying to run but I am getting this error after building the project. Class not found junitwebapp.JWebUnitTest
Please help
java.lang.NoClassDefFoundError: org/apache/xml/utils/PrefixResolver at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:763) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration.(JavaScriptConfiguration.java:377) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.(JavaScriptEngine.java:143) at com.gargoylesoftware.htmlunit.WebClient.init(WebClient.java:237) at com.gargoylesoftware.htmlunit.WebClient.(WebClient.java:211) at net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.createWebClient(HtmlUnitTestingEngineImpl.java:862) at net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.initWebClient(HtmlUnitTestingEngineImpl.java:871) at net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.beginAt(HtmlUnitTestingEngineImpl.java:212) at net.sourceforge.jwebunit.junit.WebTester.beginAt(WebTester.java:234) at net.sourceforge.jwebunit.junit.JWebUnit.beginAt(JWebUnit.java:167) at junitwebapp.JWebUnitTest.testLoginPage(JWebUnitTest.java:24) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: java.lang.ClassNotFoundException:… Read more »
It’s not working, i have tried by all possible ways
Except the correct one