這是本文件的舊版!
Mock partial static method with PowerMockito
Problem
我們可以透過PowerMock的mockStaticPartial去mock部分的static method:
PowerMock.mockStaticPartial(System.class, "getProperty"); System.getProperty("test"); PowerMock.expectLastCall().andReturn("test").anyTimes(); PowerMock.replayAll(); System.out.println(System.getProperty("test")); PowerMock.verifyAll();如果想用PowerMockito該如何做呢? 我們可以使用spy:
How to?
PowerMockito.spy(System.class); PowerMockito.doReturn("test").when( System.class, "getProperty", "test"); System.out.println(System.getProperty("test"));另一種寫法如下:
PowerMockito.spy(System.class); PowerMockito.doReturn("test").when( System.class); System.getProperty("test"); System.out.println(System.getProperty("test")); PowerMock.verifyAll();
如果是沒任何回傳值的method,可以使用PowerMockito.doNothing()。
友藏內心獨白: 實際應用會遇到更多問題的!
Reference