How to suppress and verify private static method calls?

I am stumbling about testing JUnit right now and need some help. So I got this class with static methods that will refactor some objects. To simplify, I made a small example. This is my Factory class:

class Factory { public static String factorObject() throws Exception { String s = "Hello Mary Lou"; checkString(s); return s; } private static void checkString(String s) throws Exception { throw new Exception(); } } 

And this is my test class:

 @RunWith(PowerMockRunner.class) @PrepareForTest({ Factory.class }) public class Tests extends TestCase { public void testFactory() throws Exception { mockStatic(Factory.class); suppress(method(Factory.class, "checkString")); String s = Factory.factorObject(); assertEquals("Hello Mary Lou", s); } } 

Basically, I tried to ensure that the private checkString () method should be suppressed (therefore, no exception was thrown), and I also needed to verify that the checkString () method was actually called in the factorObject () method.

UPDATED : Suppression works correctly with the following code:

 suppress(method(Factory.class, "checkString", String.class)); String s = Factory.factorObject(); 

... however, it returns me NULL for the string "s". Why is this?

+4
source share
2 answers

Well, I finally found a solution to all the problems. If someone encounters similar problems, here is the code:

 import junit.framework.TestCase; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.times; import static org.powermock.api.support.membermodification.MemberModifier.suppress; import static org.powermock.api.support.membermodification.MemberMatcher.method; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.verifyPrivate; @RunWith(PowerMockRunner.class) @PrepareForTest(Factory.class) public class Tests extends TestCase { public void testFactory() throws Exception { mockStatic(Factory.class, Mockito.CALLS_REAL_METHODS); suppress(method(Factory.class, "checkString", String.class)); String s = Factory.factorObject(); verifyPrivate(Factory.class, times(1)).invoke("checkString", anyString()); assertEquals("Hello Mary Lou", s); } } 
+7
source

Yo can do it like:

 PowerMockito.doNothing().when(Factory.class,"checkString"); 

You can find more information: http://powermock.googlecode.com/svn/docs/powermock-1.3.7/apidocs/org/powermock/api/mockito/PowerMockito.html

Edit:

 ClassToTest spy = spy(new ClassToTest ()); doNothing().when(spy).methodToSkip(); spy.methodToTest(); 
+2
source

Source: https://habr.com/ru/post/1479881/


All Articles