Powermock verify private static method call in non static method

喜欢而已 提交于 2019-12-05 02:20:28

问题


Dear stackoverflow comrades, I again have a problem in getting a specific PowerMock / Mockito case to work. The issue is, that I need to verify the call of a private static method, which is called from a public non-static method. A similar example I posted previously on How to suppress and verify private static method calls?

This is my code:

class Factory {

        public 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 testclass:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {

    public void testFactory() throws Exception {

        Factory factory = mock(Factory.class);
        suppress(method(Factory.class, "checkString", String.class));
        String s = factory.factorObject();
        verifyPrivate(factory, times(8000)).invoke("checkString", anyString());
    }
}

The problem here is, that the Test is successful, but it shouldn't be. It shouldn't be because the private static method should be called exactly 1 times. But no matter what value I put in times(), it always verifies it as true... halp :(


回答1:


Ok, I think I found the answer, but it was a headache. Rudy gave me the final hint with using using a spy, but it was still not trivial (although the solution looks "baby-easy"). Here is the complete solution:

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.spy;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {

    public void testFactory() throws Exception {

        Factory factorySpy = spy(new Factory());
        String s = factorySpy.factorObject();
        doNothing().when(factorySpy, "checkString", anyString());
        verifyPrivate(factorySpy, times(1)).invoke("checkString", anyString()); 
    }
}


来源:https://stackoverflow.com/questions/16515809/powermock-verify-private-static-method-call-in-non-static-method

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