During Unit Testing in a Play Scala project, there arises a need to Mock certain Objects or Traits which are used in the unit, so that the unit being tested has a consistent interaction with its outside dependencies. But due to tight coupling or external dependencies, objects cannot be tested as a unit. So, we need to mock those external dependencies by adding fake external dependencies to it.
This can be done with the help of various mocking frameworks like Mockito, EasyMock or jMock. Selecting an appropriate mocking framework depends on the application that is being built.
This blog will tell you how to use Mockito for mocking objects or traits in a Play Scala project along with ScalaTest.
Mockito is an open source testing framework for Java/Scala released under the MIT License. The framework allows the creation of test double objects (mock objects) in automated unit tests for the purpose of Test-driven Development (TDD).
To use Mockito in a Play Scala project follow these easy steps & you are done.
1. Add following dependencies to build.sbt ( or build.scala for version Play 2.1.x or earlier).
First one is for Scalatest and second one is for Mockito.
2. Import following libraries in your unit testing code.
Also, import the necessary Scalatest libraries required for Unit Testing of your application
3. Now here is an example code of a test case using Mockito.
In this example we want to test addUser function(unit) of userController.scala.
addUser’s definition is as follows :-
As we can see that addUser function of userController.scala is dependent on insertUser & searchUserByEmail functions to add & search new user to/from database. But, while Unit Testing we want to test only addUser function of userController.scala & not insertUser function. So, to mock insertUser function, we made a mock object mockUserDALObject which mocked UserDALComponent.
UserDALComponent & insertUser are defined as follows :-
Then we made an object userController of UserController class, with mocked object as follows :-
Using this object we can test all units/functions of UserController without using any external dependency.
Note :- For mocking any object a Trait of that object has to be created first & a Class & Object of the unit being tested. (As we have shown in above example)
3 thoughts on “Mock Unit Testing using Mockito in Play Scala project3 min read”
You want to use ScalaTest and import org.spec2 – this is not valid as of today.
Hai can u just explain how to mock database connection unit testing using scala for spark application?
Thanks in advance
Thanks for the comment.
For mocking the database connection unit testing using Scala for Spark application, you can mock the database service that is being used in the application. But, it would be better if you could share some more details so that I can explain better as to how to achieve it.
Comments are closed.