Nivedita Velagaleti
Nivedita Velagaleti

Reputation: 167

PowerMockito verify that a static method is never called

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?

Upvotes: 4

Views: 10660

Answers (2)

sg23
sg23

Reputation: 51

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.

Upvotes: 5

Nivedita Velagaleti
Nivedita Velagaleti

Reputation: 167

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()

Upvotes: 5

Related Questions