2

I'm using scalatest and when I test my code, I want to replace an implementation of a function to return something else when running tests.

In JavaScript its really simple and I thought I could do the same in scala. So what I want is something like this:

object Module {
  private def bar(): Int = {
     5
  }

  def foo(): Unit = {
    println(bar())
  }
}

And the test will be something like that (dont mind the syntax, you get the idea)

class Test extends FunSpec {
   mock(Module.bar, () => 1)
   describe("Test") {
      it("Test") {
         Module.foo() // will print 1
      }
   }
}

I have searched the internet and came across scala mock libraries but none of them seemed to be able to replace the implementation of a method. In every library you have to defined your mock in the test and pass it on to the code, but I don't want to do that.

Is there anyway to achieve this?

Thank you.

2 Answers 2

2

You can't mock Object in Scala, because it's like a static class in java (which you can't mock either). (and you can't mock scala objects not in mockito nor scalamock (maybe in their next version)).

But, if you change your object Module to class Module, you can mock this function easily (using mockito):

val mockModule = mock[Module]
when(mockModule.bar()).thenReturn(1)
Sign up to request clarification or add additional context in comments.

1 Comment

its still not what I want, I dont want to create an instance of the class Im mocking in my tests. My main method is using a function from an object/class and I want to mock that function, I can't pass the main method an instance of a mock.
1

You can do a fake class that has that function and put the value you want, if you dont want to use mocks, like this:

trait SMT{
 def bar: Int
}

class RealImpl extends SMT{
def bar: Int = 5
}

class FakeImpl extends SMT{
def bar: Int = 1
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.