简体   繁体   English

any(object.class)在Mockito中抛出null

[英]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 第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? 在任何情况下any(object.class)如何都可以为NULL,因为any仅仅意味着返回任何东西?

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. 调用方法(hasErrors()时,不能使用null参数调用ThrowErrorIfExists。这与任何模拟都没有关系,但这只是方法中的错误。

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". 然后,您可以使用任何对象调用throwErrorIfExists来触发“不执行任何操作”。

I think you are misusing the any() method. 我认为您正在滥用any()方法。 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. 如果要使用任意对象调用方法,则应在测试中创建对象并将其传递any()并非只是为您创建对象的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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