DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • IntelliJ Integration for Mockito
  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test
  • Page Object Model for Performance Testing With Gatling
  • Unit Testing Static Methods With Mockito

Trending

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Coding
  3. Languages
  4. Beginners Guide to Mocking in Scala

Beginners Guide to Mocking in Scala

Unit test cases are one of the most important parts of an application.

By 
Anjali Sharma user avatar
Anjali Sharma
·
Updated Jan. 17, 20 · Presentation
Likes (6)
Comment
Save
Tweet
Share
43.7K Views

Join the DZone community and get the full member experience.

Join For Free

We all know that unit test cases are one of the most important parts of an application. No? Then, I must tell you that unit testing is one of the earliest tests to be performed on the unit of code, and the earlier the defects are detected, the easier it is to fix. It reduces the difficulties of discovering errors contained in more complex pieces of the application.

So where does mocking come into the picture? Why do we need it? And how do we understand what we should mock while writing unit test cases? Answers to these questions are right below in this blog.

You may also like: A Guide to Mocking With Mockito

A Look at Mocking

There are programs that do not have any dependencies on external classes. Consider a program that has a method that prints “Hello, World.” Now, this program does not depend on any external classes. However, in real-world applications, classes have dependencies. Those dependencies may be some services and those services may have dependencies on some database objects and the list goes on. The main point of writing unit test cases is to test whether our piece of code is working without interaction with the external environment, i.e. if any method of another class has been called, then that method should be mocked.

Consider this example:

Scala




xxxxxxxxxx
1
11


 
1
class UserAction(loginService: LoginService) {
2
def displayActionsPerformed(val userId: String) {
3
     val result = loginService.getListOfActionsPerformed(userId)
4
    if(result.size > 0){
5
            return SUCCESS
6
    }
7
    else {
8
            return FAILURE
9
    }
10
  }
11
}



It’s clear from the code that the class UserAction has a dependency on LoginService. Here, if we start writing unit test cases for this class, we will start by testing the displayActionPerformed method. To do that, we should be able to write test cases for this method without testing getListOfActionsPerformed. We have to assume that getListOfActionsPerformed is tested to work as it is designed. The question is how do we test displayActionsPerformed without executing getListOfActionsPerformed? 

That is when mocking comes into the picture. The idea behind mocking is that we will create a mock object so that it can replace the real object and will act the same as the real object. The mock object expects certain methods to be called, and when that happens, it will return some expected result.

In this example, we were having trouble to write unit test cases because we did not really want to execute getListOfActionsPerformed. So now, with the help of mocking, we can mock the  LoginService class and create a mock object.

This mock object will call the getListOfActionsPerformed method with userId parameter and it will return say, a list of actions. Now we can easily test the displayActionsPerformed method as we have the result of its dependencies.

Example of Mocking in Scala Using Mockito

Now that you all have understood the concept behind the mocking, let’s look into the Mockito library in ScalaTest.

ScalaTest’s MockitoSugar provides basic syntax sugar for Mockito. There are more choices available that we can use for mocking, such as ScalaMock, EasyMock, and JMock. In this blog, we will be discussing the Mockito framework.

First, we need to add these two library dependencies in our build.sbt file:

Java




xxxxxxxxxx
1


 
1
libraryDependencies ++= Seq ( "org.scalatest" %% "scalatest" % "3.0.1" % "test", "org.mockito" % "mockito-core" % "2.8.47" % "test" )



Now, considering our previous example, let’s write test cases for it using Mockito.

Scala




xxxxxxxxxx
1
13


 
1
Class UserActionSpec extends WordSpec with Matchers with MockitoSugar {
2
 val mockedLoginService = mock[LoginService]
3
 val userAction = new UserAction(mockedLoginService)
4
 
          
5
“UserAction#displalyActionsPerformed” should {
6
 
          
7
 “ return SUCCESS” in {
8
 when(mockedLoginService.getListOfActionsPerformed(any[String])) thenReturn List(“user logged in”, “user updated profile”)
9
 val result = userAction.displayActionsPerformed(randomUserId) 
10
 result shouldBe SUCCESS
11
  }
12
 }
13
}
10
 result shouldBe SUCCESS



Here:

  1. We mocked our LoginService class upon which UserAction depends. 
  2. While creating an object for UserAction class we passed on the mocked parameter. 
  3. We can see how easily we can stub methods using Mockito functions: when and thenReturn 
  4. Mockito also allows us to match against any argument value (as seen in the above example, how we have used  any[String] as a matcher for userId parameter:  when(mockedLoginService.getListOfActionsPerformed(any[String])). It also comes with regex matchers and allows us to write custom matchers.
  5. To throw exceptions with Mockito, we simply need to use the thenThrow(….) function. Here is how it can be done,
Scala




xxxxxxxxxx
1
14


 
1
Class UserActionSpec extends WordSpec with Matchers with MockitoSugar {
2
val mockedLoginService = mock[LoginService]
3
val userAction = new UserAction(mockedLoginService)
4
 
          
5
“UserAction#dispalyActionsPerformed” should {
6
 
          
7
 “ return error” in {
8
 when(mockedLoginService.getListOfActionsPerformed(any[String])) thenThrow(
9
   new RuntimeException())
10
 intercept[RuntimeException]{userAction.displayActionsPerformed(randomUserId)
11
   }
12
  }
13
 }
14
}



This was all about mocking. For further details on the Mockito framework, you can read it more about it on Mockito User Guide.

This article was first published on the Knoldus blog.

Further Reading

[DZone Refcard] Mockito

A Guide to Mocking With Mockito

Unit Testing With Mockito

unit test Scala (programming language) Mockito Mock object Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • IntelliJ Integration for Mockito
  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test
  • Page Object Model for Performance Testing With Gatling
  • Unit Testing Static Methods With Mockito

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!