Reputation: 503
Is it possible to return a different type using when-return in mockito.
my function
m.findDocument(id)
returns a document based on id
which I am converting to string for further processing.
But, for testing I am fetching the string from a id file. So, effectively I want that string to be returned when the function is called like below :
when(m.findDocument(id)).thenReturn('that_string_from_id_file');
Since, one is of document type and other of String, is there way in mockito I can do the same ?
Thanks
Upvotes: 1
Views: 4042
Reputation: 140623
Thing is: using a mocking framework doesn't change the Java language.
When the signature of a method is public Foo bar()
- then even when calling bar()
on a mocked object, that method has to return an instance of Foo. You can't use mocking to silently change the declared return type of a method.
But of course, you can do:
Document mockedDocument = mock(Document.class);
DocumentFinder mockedFinder = mock(DocumentFinder);
when(mockedFinder.findDocument(id)).thenReturn(mockedDocument);
when(mockedDocument.getSomeInfo()).thenReturn("that string");
But please note: you would only mock that Document instance in case you can't use a "real" Document instance. Your goal should be to only use mocking where it is impossible/too-hard without dealing with mocks.
Upvotes: 3
Reputation: 1090
No. Depending on whether you use when+thenReturn or doReturn/doAnswer, you'll either get a compilation error or a ClassCastException.
What you can do is return a mock document from the method, and then return the test string when the mock is 'converted'.
Upvotes: 0