在Java中,如何模拟使用ServiceLoader加载的服务? [英] In Java, how can I mock a service loaded using ServiceLoader?
本文介绍了在Java中,如何模拟使用ServiceLoader加载的服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个遗留Java应用程序,该应用程序具有类似这样的代码
I have a legacy Java application that has code something like this
ServiceLoader.load(SomeInterface.class)
,我想提供SomeInterface的模拟实现以供此代码使用.我使用了模拟嘲笑框架.
and I want to provide a mock implementation of SomeInterface for this code to use. I use the mockito mocking framework.
不幸的是,我无法更改旧版代码,也不想静态添加任何内容(例如,向META-INF添加内容).
Unfortunately I am unable to change the legacy code, and I do not wish to add anything statically (eg. adding things to META-INF).
是否有一种简单的方法可以在测试中执行此操作,即在测试运行时?
Is there an easy way to do this from within the test, ie. at runtime of the test?
推荐答案
您可以使用 PowerMockito 与Mockito一起模拟静态方法:
You can use PowerMockito along with Mockito to mock static methods:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ServiceLoader.class)
public class PowerMockingStaticTest
{
@Mock
private ServiceLoader mockServiceLoader;
@Before
public void setUp()
{
PowerMockito.mockStatic(ServiceLoader.class);
Mockito.when(ServiceLoader.load(Mockito.any(Class.class))).thenReturn(mockServiceLoader);
}
@Test
public void test()
{
Assert.assertEquals(mockServiceLoader, ServiceLoader.load(Object.class));
}
}
这篇关于在Java中,如何模拟使用ServiceLoader加载的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文