我正在尝试从 java.util.concurrent 包中模拟 ExecutorService 和 Executors 。
如果我尝试在我模拟对象的同一类(测试类)中获取对象,我能够获取模拟对象。但是,如果我尝试在不同的类(我要测试的类)中获取模拟对象,那么它会从 java.util.concurrent 返回实际对象。以下是代码片段。
我要测试的课程:
public class MyClass
{
public void myMethod()
{
ExecutorService executorService = Executors.newFixedThreadPool(2, new MyThreadFactory());
for (int count = 0; count < 2; count++)
{
executorService.submit(new Thread());
}
}
}
class MyThreadFactory implements ThreadFactory
{
@Override
public Thread newThread(Runnable r)
{
return null;
}
}
我的测试类看起来像:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Executors.class)
public class MyClassTest
{
@Test
public void testMyMethod()
{
prepareMocks();
//Code to get mocked object (See testMethod below)
}
private void prepareMocks()
{
ExecutorService executorService = PowerMock.createMock(ExecutorService.class);
EasyMock.expect(executorService.submit(EasyMock.anyObject(Runnable.class))).andReturn(null).anyTimes();
PowerMock.mockStatic(Executors.class);
EasyMock.expect(Executors.newFixedThreadPool(EasyMock.anyInt(), EasyMock.anyObject(ThreadFactory.class))).andReturn(executorService).anyTimes();
PowerMock.replay(executorService, Executors.class);
}
}
如果 MyClassTest.testMyMethod() 如下所示,则返回模拟对象。
@Test
public void testMyMethod()
{
prepareMocks();
//Following code reurned mocked instance of ExecutorService
ExecutorService executorService = Executors.newFixedThreadPool(2, new MyThreadFactory());
for (int count = 0; count < 2; count++)
{
executorService.submit(new Thread());
}
}
但是,如果我将测试方法更改为调用 myClass.myMethod(),它将返回实际实例而不是 myMethod() 中的模拟实例。
@Test
public void testMyMethod()
{
prepareMocks();
/*
* Within myClass.myMethod(), Executors.newFixedThreadPool() returns actual instance of ThreadPoolExecutor
* instead of mocked object
*/
MyClass myClass = new MyClass();
myClass.myMethod();
}
我期望在 myClass.myMethod 中获得一个模拟的 Executors/ExecutorService 实例。
这是预期的行为吗?谁能解释这种行为?我错过了什么吗?