Answer the question
In order to leave comments, you need to log in
Why does the test only pass if two mocks of the same type are declared (one is not used)?
I have a mock method that should throw an error when called - for some reason it doesn't work. But when I add one more exactly the same mock to the fields, those hacked methods are worked out for me and the test passes successfully. Why can this happen?
class SomeTestClass{
@Mock
private SomeServiceImpl serviceMock;
//@Mock
//private SomeServiceImpl serviceMock2; //тест начинает корректно работать
@Spy
private MyFileTransformer fileTransformerSpy;
@Spy
private MyFileViewTransformer fileViewTransformerSpy;
@InjectMocks
private TargetService service = new TargetService();
@BeforeEach
void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
void given_when_then() {
MockMultipartFile multipartFileMock = new MockMultipartFile("fileData",
"fileName",
"text/plain",
new byte[]{});
MyFile fileTransformed = new MyFile();
when(fileTransformerSpy.convert(multipartFileMock)).thenReturn(fileTransformed);
when(serviceMock.saveFile(fileTransformed)).thenThrow(new RuntimeException());
assertThrows(RuntimeException.class,
() -> targetService.saveFile(multipartFileMock, 1L)); // ошибка из второго мока не бросилась
verifyZeroInteractions(fileViewTransformerSpy); //падает, так как не сработал мок и вызвался ненужный в данном случае метод
}
}
@Override
public FileInfoView saveFile(MultipartFile file, Long category) {
if (file == null) {
throw new MyException("Can't find file to save!");
}
MyFile fileInfo = fileTransformer.convert(file, category);
try {
MyFile myFile = service.saveFile(fileInfo); // должно упасть на этом моменте
return fileViewTransformer.convert(myFile);
} catch (Exception e) {
throw new MyException(e.getMessage());
}
}
Answer the question
In order to leave comments, you need to log in
The second category argument on this line may have been forgotten.
when(fileTransformerSpy.convert(multipartFileMock)).thenReturn(fileTransformed);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question