简体   繁体   中英

Using Mockito is there a way to throw an exception on method call when there are no valid matchers

I have a mocked class that I'd like to throw an exception rather than returning null when there are no valid matchers. Is this possible with mockito? The idea is that I've mocked the method to work with certain parameters. When none of those match, rather than returning null , throw an exception.

You can write custom org.mockito.stubbing.Answer<T> and use one with thenAnswer :

private final static String EXCEPTION_MSG = "no valid matchers";
private final static String A = "A", B = "B";
private final static Map<String, String> argsReturnVal = new HashMap<>();

static {
    argsReturnVal.put(A, B);
}

private static final Answer<String> throwAnswer = a ->
        argsReturnVal.computeIfAbsent(
                a.getArgument(0),
                mf -> { throw new IllegalArgumentException(EXCEPTION_MSG); }
        );

@Mock
private Checker<String> checker;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    Mockito.when(checker.check(Mockito.anyString())).thenAnswer(throwAnswer);
}

@Test
public void testThrow() {
    Assert.assertEquals(B, checker.check(A));
    try {
        checker.check("X-X-X");
    } catch (IllegalArgumentException ex) {
        Assert.assertEquals(EXCEPTION_MSG, ex.getMessage());
    }
}

private interface Checker<T> {
    String check(T in);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM