Controller testing

We did unit tests, we did route tests, and now is the time to add controller tests. Controller tests are similar to routes tests, but they are not the same. For instance, our controller always respond to UI pages, so we expected to create specific HTML pages based on each method. The Play framework has integration with Selenium, which is a testing framework for UIs, and a controllers that allows you to simulate web browsers, and you can do pretty much the same as you would by clicking on the pages like a real user.

So let's get started. First, we will start with RndDoubleGeneratorControllerTestSpec.

RndDoubleGeneratorControllerTestSpec.scala - RndDoubleGeneratorController tests

The RndDoubleGeneratorControllerTestSpec.scala file should contain the following code:

class RndDoubleGeneratorControllerTestSpec extends PlaySpec

with OneServerPerSuite with OneBrowserPerSuite with HtmlUnitFactory {

val injector = new GuiceApplicationBuilder()

.injector

val ws:WSClient = injector.instanceOf(classOf[WSClient]) import play.api.libs.concurrent.Execution.

Implicits.defaultContext

"Assuming ng-microservice is down rx number should be" must {

"work" in {

val future = ws.url(s"http://localhost:${port}/rnd/rxbat") .get().map { res => res.body }

val response = Await.result(future, 15.seconds) response mustBe "2.3000000000000007"

}

}

}

This class has some interesting things. For instance, we inject WSClient using Google Guice with GuiceApplicationBuilder. Secondly, we assume that the ng-microservice we created in the previous chapter is down, so we can predict the response coming from the fallback.

We call the controller using wsclient, and then we map the response to return the body content as a string. So this will be an Async Future, and in order to get the result, we use Await to wait five seconds for the response to come back. Once the response is back, we make sure the result is 2.3. If the result does not come back in 15s, the test will fail. Run the following command:

$ activator "test-only RndDoubleGeneratorControllerTestSpec"

Now you will see the following result:

All right, now we have a controller test fully working using Guice injections and the WSClient Play framework library. Let's now make controller tests for the product, image, and review controllers.

 
Source