Turn your manual testers into automation experts Request a DemoStart testRigor Free

Play Framework Testing

Play Framework Testing

Play framework or Play is an open-source web application framework that is lightweight and stateless. It’s written in Scala and built on Akka and provides predictable and minimal resource consumption for highly scalable web applications. Guillaume Bort created Play, and the initial release happened in 2007. Play framework is a direct competitor of the Spring framework in Java. Play can be usable from other programming languages compiled to JVM bytecode. Also, the Play framework uses RESTful by default and supports big data and NoSQL. The Play follows a model-view-controller architectural pattern. EA, Verizon, Linkedin, Walmart, Samsung, etc., use the Play framework.

Like with any other framework, we can perform these types of testing:
  • Unit testing
  • Integration testing
  • End to End or System testing

Unit Testing

Unit testing implies testing small pieces of code to ensure the tested function works without fail. In Play, we can do unit testing for the models, controllers, view templates, and essential actions. Unit testing differs for Java as well as Scala.

Java Unit Testing

The default framework used for unit testing is JUnit. Play provides helpers and application stubs for testing. The unit test cases are written and stored in the "test" folder and executed via the Scala build tool console. Users can run all tests in parallel or in the selective mode. A new process gets forked whenever unit testing is triggered. Users can provide custom settings via "build.sbt".

Here is a sample unit test case written in JUnit:
import static org.junit.Assert.*;
import org.junit.Test;
public class SimpleTest {
  @Test
  public void testSum() {
    int a = 1 + 1;
    assertEquals(2, a);
  }
    
  @Test
  public void testString() {
    String str = "Hello world";
    assertFalse(str.isEmpty());
  }
}

Many popular libraries are used to write assertions for unit testing, such as Hamcrest. If the test class depends on an external data access class, we may have to mock it for controlled data. Mockito library is used for mocking external data. An external library Ebean is used for the unit testing of Models. Ebean helps in adding data logically to the unit test scenarios. Play's test helpers are mainly used for the unit testing of Controllers.

Scala Unit Testing

The scala-based application provides an integration library, "ScalaTest + Play" for unit testing. The user needs to add ScalaTest + Play to the "builds.sbt". Here is a sample scalaTest+ Play unit test-case:
import org.scalatestplus.play._
import scala.collection.mutable
class StackSpec extends PlaySpec {
  "A Stack" must {
    "pop values in last-in-first-out order" in {
      val stack = new mutable.Stack[Int]
      stack.push(1)
      stack.push(2)
      stack.pop() mustBe 2
      stack.pop() mustBe 1
    }
    "throw NoSuchElementException if an empty stack is popped" in {
      val emptyStack = new mutable.Stack[Int]
      a[NoSuchElementException] must be thrownBy {
        emptyStack.pop()
      }
    }
  }
}

Internal libraries like Anorm or Slick are used for the unit testing of Models. They help in adding data logically to the unit test scenarios.

Integration Testing

Integration testing is responsible for connecting different modules, functions, or components in a system. For both Java and Scala applications, users can perform integration testing on the server or in the browser. Play provides many custom methods and classes to support integration testing, which can be found in "play.api.test" package or "play.test" package.

Testing With a Server

We need to have a test server up and running for testing in a real HTTP server. Here is a sample code for the server test in Java
public class ServerFunctionalTest extends WithServer {
  @Test
  public void testInServer() throws Exception {
     OptionalInt optHttpsPort = testServer.getRunningHttpsPort();
     String url;
     int port;
     if (optHttpsPort.isPresent()) {
        port = optHttpsPort.getAsInt();
        url = "https://localhost:" + port;
     } else {
        port = testServer.getRunningHttpPort().getAsInt();
        url = "http://localhost:" + port;
     }
     try (WSClient ws = play.test.WSTestClient.newClient(port)) {
       CompletionStage stage = ws.url(url).get();
       WSResponse response = stage.toCompletableFuture().get();
       assertEquals(NOT_FOUND, response.getStatus());
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

If multiple tests are running on the same server, the performance of the test will be high. Users can change server configurations in the "ConfiguredServer" file.

Testing In a Browser

For integration testing in the browser, the Play framework depends on the Selenium Webdriver. Let's look at Selenium integration with Play in the system testing section.

End to End / System Testing

This type of testing sits on top of the testing pyramid and ensures that the whole application works per requirements. With system testing, the user can confirm not just the controller part, but that the controller UI code also works well. In other words, it is about testing the UI layer.

E2E, or system testing, can be performed with the following:
  • Testing the controller with JUnit
  • Selenium Webdriver
  • testRigor

Testing The Controller With JUnit

Users can do system testing on the controller part using the JUnit framework. Functional tests call the "ActionInvoker" class simulating an HTTP response. The play framework routes the request, invokes the corresponding action, and sends the response. Based on the assertions the user provides, the test case gets verified.

Here s a sample test code:
import org.junit.*;
import play.test.*;
import play.mvc.*;
import play.mvc.Http.*;
import models.*;
public class ApplicationTest extends FunctionalTest {
  @Test
  public void testThatIndexPageWorks() {
      Response response = GET("/");
      assertIsOk(response);
      assertContentType("text/html", response);
      assertCharset("utf-8", response);
  }
}

Though the user can test the entire application via this method, this won't provide an accurate result as the users interact with the View, and there can be issues. Since it's not ideal for end-to-end testing, let's move to other options.

Selenium Webdriver

Selenium is a legacy open-source web automation tool for web application automation. We won't go into too many details in this article. You can learn more about Selenium here and also the limitations of Selenium here.

testRigor

testRigor is one of the most advanced AI-integrated automated tools built explicitly for end-to-end testing. It's known for being completely no-code, as well as extremely stable tests and low maintenance.

Let's write a sample script of a user adding an item to the cart:
click "Sign In"
enter email into "Email"
enter password into "Password"
click "Submit"
enter "Keyboard with Lights" into "Search" input
click "GO"
click "first" item
click "add to cart"
click "cart"
check that page contains "Keyboard with Lights"

The above example may look like a test case, but it's a test script. As you can see, there are no details of implementation, allowing for a test built truly in the UI layer. This approach allows for tests that represent an actual user's perspective, from start to finish of a flow.

Another benefit is the minimal learning curve of starting with testRigor. It's cloud-hosted, and the initial setup of a new test suite only takes a few minutes. From there, anyone on the team can build cross-browser and cross-platform functional UI tests, edit and maintain them.

Let's go through a few features in which testRigor excels over the other no-code tools:
  • tesRigor is a cloud application, so there is no extra device setup or maintenance cost
  • testRigor supports cross-platform tests across desktop applications, desktop and mobile browsers, and native mobile apps. There are many other testing types, such as API testing, performance testing, etc.
  • testRigor provides integrations with multiple issue management and test management tools like Jira, Zephyr, and X-ray.
  • Detailed test reports are available in formats like HTML, pdf, and video recordings.

Conclusion

Having a solid testing strategy is crucial, with tests on each layer allowing for optimal performance. You now have all the main tools for testing the Play application at your fingertips and can build an optimal plan of action to ensure high quality for your end users.

Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.