Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mockito with multiple calls to the same method with the same arguments

Is there a way to have a stubbed method return different objects on subsequent invocations? I'd like to do this to test nondeterminate responses from an ExecutorCompletionService. i.e. to test that irrespective of the return order of the methods, the outcome remains constant.

The code I'm looking to test looks something like this.

// Create an completion service so we can group these tasks together ExecutorCompletionService<T> completionService =         new ExecutorCompletionService<T>(service);  // Add all these tasks to the completion service for (Callable<T> t : ts)     completionService.submit(request);  // As an when each call finished, add it to the response set. for (int i = 0; i < calls.size(); i ++) {     try {         T t = completionService.take().get();         // do some stuff that I want to test     } catch (...) { }         } 
like image 830
Emma Avatar asked Nov 11 '11 00:11

Emma


People also ask

How do you inject multiple mocks of the same interface?

It makes it easier to inject mocks in tests (just call a constructor with your mocks - without reflections tools or @InjectMocks (which is useful, but hides some aspects)). In addition using TDD it is clearly visible what dependencies are needed for the tested class and also IDE can generate your constructor stubs.

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.

Does Mockito verify use equals?

Internally Mockito uses Point class's equals() method to compare object that has been passed to the method as an argument with object configured as expected in verify() method. If equals() is not overridden then java. lang.

What is difference between @mock and Mockito mock?

mock() method allows us to create a mock object of classes and interfaces. The Mockito. mock() is usually placed in the test set up method annotated with @Before in JUnit4 or @BeforeEach in JUnit 5. We called it before each test to create a new fresh mock object.


1 Answers

How about

when( method-call ).thenReturn( value1, value2, value3 ); 

You can put as many arguments as you like in the brackets of thenReturn, provided they're all the correct type. The first value will be returned the first time the method is called, then the second answer, and so on. The last value will be returned repeatedly once all the other values are used up.

like image 169
Dawood ibn Kareem Avatar answered Oct 17 '22 14:10

Dawood ibn Kareem