Let's imagine I have a following method in some service class:
public SomeEntity makeSthWithEntity(someArgs){ SomeEntity entity = new SomeEntity(); /** * here goes some logic concerning the entity */ return repository.merge(entity); }
I'd like to test the behaviour of this method and thus want to mock the repository.merge
in following manner:
when(repository.merge(any(SomeEntity.class))).thenReturn(objectPassedAsArgument);
Then mocked repository returns that what makesSthWithEntity
passed to it and I can easily test it.
Any ideas how can I force mockito to return objectPassedAsArgument
?
In Mockito, you can specify what to return when a method is called. That makes unit testing easier because you don't have to change existing classes. Mockito supports two ways to do it: when-thenReturn and doReturn-when . In most cases, when-thenReturn is used and has better readability.
One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test. I strongly recommend only using doReturn/when .
Mockito Argument Matcher - eq() When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method. when(mockFoo. bool(eq("false"), anyInt(), any(Object. class))).
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.
Or better using mockito shipped answers
when(mock.something()).then(AdditionalAnswers.returnsFirstArg())
Where AdditionalAnswers.returnsFirstArg()
could be statically imported.
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