Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Mockito to Stub methods in the same class as the class under test (CUT)

Tags:

java

mockito

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);  } 
like image 705
Sudhir Avatar asked Jan 07 '14 15:01

Sudhir


People also ask

How do you mock another method that is being tested in the same class?

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.

What is a stubbed method Mockito?

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.

What is the difference between mocking and stubbing?

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.


1 Answers

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.

like image 162
fatih Avatar answered Oct 13 '22 14:10

fatih