-1

I have an Object that may be null.

I want to verify that when an object is null, it's method is not invoked.

I wrote a test case that looks like this:

    String str = mock(String.class);
    str = null;
    verify(str, never()).length();

But Mockito replies with:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class java.lang.String
Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types

How do I verify that my a method is not invoked on a null Object?

Some Noob Student
  • 14,186
  • 13
  • 65
  • 103

1 Answers1

2

You can't use mock operations on a null object reference.

But if any method is called on your null object reference, then you'll get a NPE - this should fail your test (unless you were expecting a NPE, of course).

You can also use assertNull() to be sure that str is in fact null, if this is part of your test result.

vikingsteve
  • 38,481
  • 23
  • 112
  • 156