S
S
s2019-07-30 20:13:31
Java
s, 2019-07-30 20:13:31

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); //падает, так как не сработал мок и вызвался ненужный в данном случае метод
        }
}

tested method:
@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());
        }
    }

PS: I am using junit 5. I only call one test method. Class names have been changed for privacy purposes.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AndreyBell, 2019-07-31
@solovladys

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 question

Ask a Question

731 491 924 answers to any question