Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stubbing methods that manipulates parameters with mockito

Tags:

I have the following situation:

class Worker {     public Integer somework() {         Integer k=0;         Helper h= new Helper();         h.change(k);         return k;       } }  class Helper {   public void change(Integer k) {     //k = Some calcs   } } 

I'm making unitests for Worker and obviously I want to mock Helper class so that his change method will always put 1 into k.

My real situation is more complicated but this code represents the issue. Thanks for help.

like image 606
TryHarder Avatar asked Nov 25 '11 20:11

TryHarder


People also ask

What is stub method in 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 difference between @mock and @injectmock?

@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance. @Mock is used to create mocks that are needed to support the testing of the class to be tested. @InjectMocks is used to create class instances that need to be tested in the test class.

Can we mock interface using Mockito?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.


1 Answers

I have a method with definition like this:

class Template{    public void process(Object rootMap, StringWriter out){  .......      }  } 

I will show you how you can change/modify the "out"(StringWriter) reference.

private final Template mocktTemplate = mock(Template.class); doAnswer(new Answer<StringWriter>() {              public StringWriter answer(InvocationOnMock invocation)                     throws Throwable {                 Object[] args = invocation.getArguments();                 if (args[1] instanceof StringWriter) {                     StringWriter stringWriter = (StringWriter) args[1];                     stringWriter.write("Email message");                 }                 return null;             }         }).when(this.mocktTemplate).process(anyObject(),any(StringWriter.class)); 

Now when you do make the actual call like:

msgBodyTemplate.process(model, msgBodyWriter); 

the value of Stringbuffer ref in msgBodyWriter will be "Email message"; irrespective of it earlier value.

like image 116
omkar Avatar answered Oct 13 '22 00:10

omkar