Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do strict mocks with Mockito?

I'd like to use strict mocks, at least when developing for the first time some tests against old code, so any methods invoked on my mock will throw an exception if I didn't specifically define expectations.

From what I've come to see, Mockito if I didn't define any expectations will just return null, which will later on cause a NullPointerException in some other place.

Is it possible to do that? If yes, how?

like image 206
devoured elysium Avatar asked Nov 03 '11 23:11

devoured elysium


People also ask

What is strict stubbing in Mockito?

"Strict stubbing" is a new feature in Mockito 2 that drives cleaner tests and better productivity. The easiest way to leverage it is via Mockito's JUnit support ( MockitoJUnit ) or Mockito Session ( MockitoSession ).

What is lenient () in Mockito?

lenient() to enable the lenient stubbing on the add method of our mock list. Lenient stubs bypass “strict stubbing” validation rules. For example, when stubbing is declared as lenient, it won't be checked for potential stubbing problems, such as the unnecessary stubbing described earlier.

Can Mockito test private methods?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.

Is Mockito better than EasyMock?

method. Mockito is the most popular mocking framework used for testing Java applications. It is better than any other testing and mocking framework, such as EasyMock.


1 Answers

What do you want it to do?

You can set it to RETURN_SMART_NULLS, which avoids the NPE and includes some useful info.

You could replace this with a custom implementation, for example, that throws an exception from its answer method:

@Test
public void test() {
    Object mock = Mockito.mock(Object.class, new NullPointerExceptionAnswer());
    String s = mock.toString(); // Breaks here, as intended.
    assertEquals("", s);
}

class NullPointerExceptionAnswer<T> implements Answer<T> {
    @Override
    public T answer(InvocationOnMock invocation) throws Throwable {
        throw new NullPointerException();
    }
}
like image 183
Dave Newton Avatar answered Sep 20 '22 22:09

Dave Newton