The following recipe focuses on writing a test for our model objects. We will create a new record and add assertions to validate the object's creation. We will then use the Activator
command to run our test.
For Java, we need to take the following steps:
Edit the
ProductTest.java
file and add the following content:// add new imports import static play.test.Helpers.*; import models.*; import play.test.*; // add new test @Test public void testSavingAProduct() { running(fakeApplication(), new Runnable() { public void run() { Product product = new Product(); product.name = "Apple"; product.save(); assertNotNull(product.getId()); } }); }
Execute the new spec by running the command
test-only ProductTest
:[foo_java] $ test-only ProductTest [info] Passed: Total 2, Failed 0, Errors 0, Passed 2 [success] Total time: 2 s, completed 09 29, 14 9:33:43 PM
For Scala, we need to take the following steps:
Edit the
ProductSpec.scala
file and add the following content:import models._ import play.api.test.WithApplication "models.Product" should { "create a product with save()" in new WithApplication { val product = Product(1, "Apple") val productId = Product.save(product) productId must not be None } }
Execute the new spec by running the command
test-only ProductSpec
:[foo_scala] $ test-only ProductSpec [info] Compiling 1 Scala source to /private/tmp/foo_scala/target/scala-2.11/test-classes... [info] ProductSpec [info] [info] The 'product' string should [info] + contain seven characters [info] [info] models.Product should [info] + create a product with save() [info] [info] Total for specification ProductSpec [info] Finished in 1 second, 90 ms [info] 2 examples, 0 failure, 0 error [info] Passed: Total 2, Failed 0, Errors 0, Passed 2 [success] Total time: 4 s, completed 09 29, 14 4:28:51 PM
In this recipe, we added a new spec, where we created a new product and invoked the save()
method. We then added assertion statements to validate that the value returned by the save()
method is not equal to none. The test
command is used to run the test and displays the results of the test.