I have a service class which has 2 methods(one is public and other is protected). I am trying to unit test my code. Below is the code snippet MyServiceClass.groovy
class MyServiceClass {
public boolean myMethod1() {
// some code
boolean success = myMethod2()
// some code
}
public boolean myMethod2() {
// some logic to return true/false
return true
}
}
MyServiceClassTests.groovy
class MyServiceClassTests {
void testMyMethod1() {
// unit test code
}
}
In the above unit test code, I want to mock the myMethod2() return result which is invoked by myMethod1(), i.e., both the methods are in the same service class which is under unit test. How to mock it and get things done??
You certainly can't mock the class under test, otherwise you're just testing a mock.
You will probably be better off, moving
myMethod2()into another class. Think about whetherMyServiceClassis trying to do too much.EDIT
You have asked for an answer that doesn't require moving myMethod2()
Option 1
Create a new sub class to to be the class under test instead of MyServiceClass. Your new class should extend MyServiceClass, then you can override
myMethod2()and provide a different "test only" implementation.Option 2
It is possible to use Mockito to Spy the class under test, but this is rather an unorthodox approach.
I still recommend refactoring the code if you have the control