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 (...) { } }
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.
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.
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.
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.
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.
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