How to use soft assertions in Mockito?

2019-08-18 07:09发布

I know that we can use ErrorCollector or soft assertions (AssertJ or TestNG) that do not fail a unit test immediately.

How they can be used with Mockito assertions? Or if they can't, does Mockito provide any alternatives?


Code sample

verify(mock).isMethod1();
verify(mock, times(1)).callMethod2(any(StringBuilder.class));
verify(mock, never()).callMethod3(any(StringBuilder.class));
verify(mock, never()).callMethod4(any(String.class));

Problem

In this snippet of code if a verification will fail, then the test will fail which will abort the remaining verify statements (it may require multiple test runs until all the failures from this unit test are revealed, which is time-consuming).

2条回答
Emotional °昔
2楼-- · 2019-08-18 07:41

Since Mockito 2.1.0 you can use VerificationCollector rule in order to collect multiple verification failures and report at once.

Example

import static org.mockito.Mockito.verify;
import org.junit.Rule;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.VerificationCollector;

// ...

    @Rule
    public final VerificationCollector collector = MockitoJUnit.collector();


    @Test
    public void givenXWhenYThenZ() throws Exception {
        // ...
        verify(mock).isMethod1();
        verify(mock, times(1)).callMethod2(any(StringBuilder.class));
        verify(mock, never()).callMethod3(any(StringBuilder.class));
        verify(mock, never()).callMethod4(any(String.class));
    }

Known issues

This rule cannot be used with ErrorCollector rule in the same test method. In separate tests it works fine.

查看更多
▲ chillily
3楼-- · 2019-08-18 07:55

Using Soft assertions you could do :

softly.assertThatThrownBy(() -> verify(mock).isMethod1()).doesNotThrowAnyException();
softly.assertThatThrownBy(() -> verify(mock, times(1)).callMethod2(any(StringBuilder.class))).doesNotThrowAnyException();
softly.assertThatThrownBy(() -> verify(mock, never()).callMethod3(any(StringBuilder.class))).doesNotThrowAnyException();
softly.assertThatThrownBy(() -> verify(mock, never()).callMethod4(anyString())).doesNotThrowAnyException();

If one or more of your mockito assertions fail, it will trigger an exception, and softAssertion will do the reporting job.

查看更多
登录 后发表回答