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.
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.
@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.
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.
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.
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