【发布时间】:2017-11-16 03:22:51
【问题描述】:
我正在为单例 Java 类编写单元测试(使用 JUnit 和 Mockito)。我无法更改类实现本身。
使用 PowerMockito,它就像这样(并且有效):
@Mock
private TheSingleton theSingleton;
@Before
public final void setUp()
throws Exception
{
MockitoAnnotations.initMocks( this );
PowerMockito.mockStatic( TheSingleton.class );
when( TheSingleton.getInstance() ).thenReturn( theSingleton );
...
}
要求不使用使用 PowerMock 或 PowerMockito 或任何其他静态模拟 API 重写测试。由于我无法将单例类更改为使用依赖注入,因此我不确定这样做的好方法是什么。
任何帮助将不胜感激。
【问题讨论】:
标签: java unit-testing singleton mockito powermock