PowerMockito verify that a static method is never called

懵懂的女人 提交于 2020-03-03 07:03:28

问题


I am writing a JUnit test to verify that a static method (MyClass.myMethod()) is never invoked in the method flow. I tried doing something like this:

  PowerMockito.verifyStatic(Mockito.never());
  MyClass.myMethod(Mockito.any());

In doing so I receive an UnfinisedVerificationException. How do I test that MyClass.class has no interactions whatsoever in the method execution?


回答1:


UnfinishedVerificationException will occur if the Class is not mocked yet but you are trying to verify the invocation of its static method.

PowerMockito.mockStatic(MyClass.class);
underTest.testMethod();
PowerMockito.verifyStatic(Mockito.never());
MyClass.myMethod(Mockito.any());
.
.
.

This should succeed if the flow never encounters a call to MyClass.myMethod()




回答2:


I was not able to get this to work using Mockito.never().

I was able to get this to work using an instance of NoMoreInteractions.

After calling the production method, and verifying all calls to the static method that was mocked, call verifyStatic with an instance of NoMoreInteractions as the second argument.

mockStatic(MyClassWithStatic.class);
when(MyClassWithStatic.myStaticMethod("foo")).thenReturn(true);

instanceOfClassBeingTested.doIt();

verifyStatic(MyClassWithStatic.class, times(1));
MyClassWithStatic.myStaticMethod("foo");

verifyStatic(MyClassWithStatic.class, new NoMoreInteractions());
MyClassWithStatic.myStaticMethod(Mockito.anyString());

If the class being tested calls myStaticMethod with anything other than foo, the test fails with a message stating that there are unverified invocations.



来源:https://stackoverflow.com/questions/50255565/powermockito-verify-that-a-static-method-is-never-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!