ProductService.scala - FIX the code issue

That's the great thing about tests: they show issues in our code so that we can fix them before the code goes to production and affects the user experience. To fix the last test, we need to go to the ProductService class and fix a method. This is how we fix it:

private def validateId(id:Long):Unit = { val entry = inMemoryDB.get(id)

if (entry==null || entry.equals(None)) throw new

RuntimeException("Could not find Product: " + id)


All set now, everything is okay. The Play framework supports testing for expected exceptions using the intercept function to pass the expected exception, Let's run the test in the console using the activator command.

$ activator "test-only ProductServiceTestSpec"

After executing this command, we get the following:

ImageServiceTestSpec.scala - ImageService Test

Alright, Now we can add tests for ImageService as follows:

class ImageServiceTestSpec extends PlaySpec {

"ImageService" must {

val service:IImageService = new ImageService "insert a image properly" in {

val image = new models.Image(Some(1),Some(1),




"update a image" in {

val image = new models.Image(Some(2),Some(1), "") service.update(1, image)


"not update because does not exist" in { intercept[RuntimeException]{ service.update(333,null)



"find the image1" in { val image = service.findByld(l) mustBe Some(l) image.get.productId mustBe Some(1)

image.get.url mustBe ""


"find all" in {

val reviews = service.findAll() reviews.get.length mustBe 1 reviews.get(0).id mustBe Some(1) reviews.get(0).productId mustBe Some(1)

reviews.get(0).url mustBe ""


"remove 1 image" in {

val image = service.remove(1) image mustBe true

val oldImage = service.findById(1) oldImage mustBe None


"not remove because does not exist" in { intercept[RuntimeException]{ service.remove(-1)





So these are the BDD tests for ImageService. We have covered all the available functions on the service. Like in the ProductService class, we also have tests for unfortunate scenarios where we expect exceptions to happen.

Sometimes, we need to call more than one function to test a specific function or a specific test case. For example, in "remove 1 image", we first delete an image. Our test case checks for an image that does not exist. Let's run the tests on the Activator console.

$ activator "test-only ImageServiceTestSpec"

The following result will be obtained:

< Prev   CONTENTS   Source   Next >