How to check whether a method returns a null?

1.7k Views Asked by At
Assert.assertThat(refVar.method(), is(null)); 

Does the code is(null) correct to check whether the refVar.method() returns a null? If not, how do i check whether something is a null or not? I've tried aNull but the IDE says this method does not exist, i tried importing Matcher.* already. Please help.

2

There are 2 best solutions below

0
Shrembo On

Null or Not Null

The matchers aNull<T>(Class<T>) and aNonNull<T>(Class<T>) specify that an argument is null or is not null, respectively.

The following code specifies that the method "doSomething" must be called with two strings, the first must be null and the second must be not null.

oneOf (mock).doSomething(with(aNull(String.class)), aNonNull(String.class)));

Check this jMock Matchers for more clarifications

0
Progman On

It looks like that jMock is not the right tool to do this. Mocks are usually used to have some kind of dummy implementation of some class/interfaces instead of having the actual production implementation of some class/interface in your unit tests. With jMock you write code like:

When method foo is called with the argument 42, the mock of that object/interface should return the string "abc".

However, jMock does not check if an existing class will return the value you expect. That is something "basic" JUnit tests will do. So you instance the class you want to check and call the methods you want to verify that it does indeed return the values it should return. So you write something like:

Assertions.assertNull(refVar.method());

This will verify that the return value of the refVar.method() call right there will return null. There is no need for jMock here.