How to use soft assertions in Mockito?

℡╲_俬逩灬. 提交于 2019-12-11 17:08:58

问题


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).


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/53694359/how-to-use-soft-assertions-in-mockito

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!