问题
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