Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito - returning the same object as passed into method

Tags:

java

mockito

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 ?

like image 882
LechP Avatar asked Oct 02 '14 13:10

LechP


People also ask

How do I return an object in Mockito?

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.

What is the difference between doReturn and thenReturn in Mockito?

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 .

What is EQ Mockito?

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

What is stubbing 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.


1 Answers

Or better using mockito shipped answers

when(mock.something()).then(AdditionalAnswers.returnsFirstArg()) 

Where AdditionalAnswers.returnsFirstArg() could be statically imported.

like image 58
Brice Avatar answered Sep 21 '22 16:09

Brice