Testing with Junit

If you come from a Java background, it is highly possible that you have already worked with Junit. It's possible to test with Junit using the Scala and Play framework. However, this is not the best practice when we are creating applications with the Play framework, since it favors Behavior Driven Development (BDD) testing with Scala Spec. For this chapter, we will cover how to perform all sorts of test using BDD and Play. Right now, let's take a look at how we can do unit testing with Junit before we move to BDD.


@Suite.SuiteClasses(Array(classOf[JunitSimpleTest])) class JunitSimpleSuiteTest

class JunitSimpleTest extends PlaySpec with AssertionsForJUnit {

@Test def testBaseService() { val s = new ProductService val result = s.findAll() assertEquals(None, result) assertTrue( result != null)

println("All good junit works fine with ScalaTest and Play")



So what we have in the preceding code is a class that extends PlaySpec, and adds a trait called AssertionForJunit. Why don't we have the classical Junit class here? Because the Play framework is set up to run Scala tests, so this bridge allows us to run Junit by ScalaTest Play framework constructs.

Then we have a test function called testBaseServer , which uses the @Test annotation from JUnit. Inside the test method, we create an instance of ProductService, and then we call the function findAll.

Finally, we have assertions that will check if the result is what we are expecting. So we don't have products, because we did not insert them earlier. Hence, we expect to have None as the response, and the result should also not be null.

You can run this in your console using the following command:

$ activator "test-only JunitSimpleTest"

You will see the result shown in the next screenshot:

As you can see, our test was executed without any issues. It's also possible to run this test and a normal test in Junit using the Eclipse IDE. You just right-click on the file and select Run As: Scala Junit Test; refer to the following screenshot:

< Prev   CONTENTS   Source   Next >