Ram*_*esh 1 junit unit-testing easymock mocking powermock
我想模拟静态方法以及类的非静态方法.我的来源看起来像:
Run Code Online (Sandbox Code Playgroud)
public class XDSUtilityManager
{
private static XDSUtilityManager xdsUtilMgr = new XDSUtilityManager();
private XDSUtilityManager()
{
xdsUtilMgrImpl = new XDSUtilityManagerImpl();
}
public static XDSUtilityManager getInstance()
{
return (xdsUtilMgr == null ) ? new XDSUtilityManager() : xdsUtilMgr;
}
public XMLDocument getXMLDocument(final String absoluteKey, final XDSClient xdsClient)
{
return getXMLDocument(absoluteKey, xdsClient, false);
}
}
I want to mock static method getInstance(). I want getInstance() to return mock object of XDSUtilityManager class. Also I want to mock getXMLDocument() which is not static.
And in my testCase I tried following:
XMLDocument xmlDocument = PowerMock.createMock(XMLDocument.class);
XDSUtilityManager xdsUtilityManager = PowerMock.createPartialMock(XDSUtilityManager.class,"getXMLDocument");
PowerMock.mockStaticPartial(XDSUtilityManager.class, "getInstance");
expect(XDSUtilityManager.getInstance()).andReturn(xdsUtilityManager).anyTimes();
expect(xdsUtilityManager.getXMLDocument((String)anyObject(), anyObject(XDSClient.class))).andReturn(xmlDocument).anyTimes();
PowerMock.replay(xdsUtilityManager);
PowerMock.replay(xmlDocument);
public class XDSUtilityManager
{
private static XDSUtilityManager xdsUtilMgr = new XDSUtilityManager();
private XDSUtilityManager()
{
xdsUtilMgrImpl = new XDSUtilityManagerImpl();
}
public static XDSUtilityManager getInstance()
{
return (xdsUtilMgr == null ) ? new XDSUtilityManager() : xdsUtilMgr;
}
public XMLDocument getXMLDocument(final String absoluteKey, final XDSClient xdsClient)
{
return getXMLDocument(absoluteKey, xdsClient, false);
}
}
Run Code Online (Sandbox Code Playgroud)
But things are not working as expected. Please help
我发现这样做的最简单方法是使用PowerMockito.PowerMockito是Mockito和PowerMock的组合,它允许模拟静态对象.
我使用的模式是使用mock你的静态getInstance()来返回非静态模拟的副本,然后你可以正常扩展.使用PowerMockito的一个例子是:
@RunWith(PowerMockRunner.class)
@PrepareForTest({SingletonObject.class})
public class SingletonTester {
@Mock
private SingletonObject singleMock;
@Before
public void setup(){
// initialize all the @Mock objects
MockitoAnnotations.initMocks(this);
// mock all the statics
PowerMockito.mockStatic(SingletonObject.class);
}
@Test
public void mockTester(){
// Mock the static getInstance call to return the non-Static Mock
Mockito.when(SingletonObject.getInstance()).thenReturn(singleMock);
// Mock the non static version as normal
PowerMockito.when(singleMock.nonStaticMethodCall()).thenReturn("Whatever you need.");
//..........
}
}
Run Code Online (Sandbox Code Playgroud)
getInstance()获取singleton对象的静态调用将返回您定义的实例化模拟对象.一旦告诉静态返回什么,就可以继续正常模拟非静态调用.