简体   繁体   中英

any(object.class) throwing null in mockito

I have the following class:

mockStatic(Exception.class); 

PowerMockito.doNothing().when(Exception.class);

Exception.throwErrorIfExists(any(Object.class)); // line3

In exception class,method is defined as follows:

static void throwErrorIfExists(def model){

  if(model.hasErrors())
    throwError(model)
  }

The following exception is thrown at line 3: Cannot invoke method hasErrors() on null object java.lang.NullPointerException: Cannot invoke method hasErrors() on null object

How can any(object.class) be NULL in any circumstances because any simply means return any anything?

You can't invoke ThrowErrorIfExists with a null parameter, as you invoke a method (hasErrors() on it. This has nothing to do with any mocking, but it is just an error in your method.

You use a matcher to call the method

Exception.throwErrorIfExists(any(Object.class));

which is quite strange; matchers are used to configure the behaviour of a mock like

PowerMockito.doNothing().when(Exception.throwErrorIfExists(any(Object.class)));

Then you can call throwErrorIfExists with any object to trigger the "do nothing".

I think you are misusing the any() method. This method exists so that you can verify interactions with mocks, eg you can say:

// checks yourMethod() was invoked with any argument
verify(mockedObject).yourMethod(any(SomeClass.class));

If you want to call your method with some arbitrary object, you should create the object in your test and pass it in. any() is not a method that just makes objects for you.

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