I have a case class in scala with new object for another class like(for simplicity, it's not returning anything say):
case class A() extends Logging with Serializable {
def run(escid: String): Unit = {
new B("value").call()
}
}
How can I write unit test of run method such that I can stub call to do nothing.
I am using mockito-scala and couldn't find any example to mock constructor . Is there any way I can write scala test with mocking construcor.
TL;DR
From the provided example in the question
since mockito 3.4, you can use
Mockito.mockConstruction
. An example of how to use it in your case would beThis seems like a design problem. Having a concrete class being created inside another class make things tightly coupled. Applying dependency injection will give you more flexibility and will let you create tests that are easier to setup and write.
In scala you have the primary constructor and the auxiliary constructor
then you can instance the class like this
Unless you have a really complex logic in
myField
ormyMethod
, just passing mocks as parameters in the constructor would be enough to validate the expected results based on the inputs.You can mock constructors using PowerMock or Mockito since version 3.4
Also you should consider if it is possible to refactor your code before start mocking constructors