Functional Programming, Simpler Unit Testing Part 3

Leandro Bolívar
Pragmatic Scala
Published in
2 min readApr 6, 2016

In the previous part of the series (Functional Programming, Simpler Unit Testing Part 2) I illustrated how we can use mocks and stubs to handle tests for functions that depend on objects that produce side effects. Now we are going to take a look on how we can partially mock classes in order to stub its functions and we can do that with spies, also defined in specs2.

There are times when we like to assert function calls that we pass to a higher order function but with simple mocks we can’t do a stub of methods that belong to the class we are testing, here is where spies come in handy. We can spy on our tested class and stub the methods we want while normally testing the higher order functions. I simplified the code for AccountServicesSpec2 so that the only test that is defined is for the higher order function applyInterest:

There are some details to point out:

  • In specs2, there is a different way to stub spies. We need to use the doReturn/when methods when specifying the return value of the function when it gets called.
  • Since we are now stubbing the methods that produce side effects, there will be no calls to the mocks we defined for AccountRepository and IntegrationServices so we assert that in fact none of the methods of those dependencies gets called.
  • There is no need to define a partial function for adding interest, we just use the actual stubbed method of the spied class.

By using spies we extended the reach of our test for the applyInterest function since it allowed us to assert the calls of methods that we will actually use in the execution of AccountServices, in my humble opinion, it is a very useful trait. This last part of the series wraps it since it was intended to give just a glance of specs2. I remind you that there are examples you can check out if you want to know all you can do with this library.

--

--

Leandro Bolívar
Pragmatic Scala

The question isn't who is going to let me; it's who is going to stop me. Ayn Rand.