I am trying to test some legacy code using Mockito, and the method is a of type void.
I have stubbed out a lot of the calls to methods in other classes, this works fine. However, I also need to be able to stub out certain calls to other methods inside the same class.
Currently this is not working.
e.g. My Class is like below:
public class Test { public Test(dummy dummy) { } public void checkTask(Task task, List <String> dependencyOnLastSuccessList) throws TaskException { callToOtherClass.method1 // This works fine, I can stub it using mockito updateAndReschedule(Long id, String message) // call to method in same class, I cannot stub it } public void updateAndReschedule(Long id, String message) { //method logic..... } }
This is my testClass showing what I have at the minute:
@Test public void testMyMethod() { Test testRef = new Test(taskJob); Test spy = spy (testRef); // when a particular method is called, return a specific object when(callToOtherClass.method1).thenReturn(ObjectABC); //doNothing when my local method is called doNothing().when(spy).updateAndReschedule(1, "test"); //make method call spy.checkTask(ts, taskDependencies); }
We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.
A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.
Stubbing, like mocking, means creating a stand-in, but a stub only mocks the behavior, but not the entire object. This is used when your implementation only interacts with a certain behavior of the object.
You should instantiante testRef as follows:
Test testRef = new Test(taskJob) { public void updateAndReschedule(Long id, String message) { //do nothing } };
No need for the spy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With