In Java, how to use serviceloader to simulate a loaded service?
•
Java
I have a traditional Java application that has such code
ServiceLoader.load(SomeInterface.class)
I want to provide a code to simulate the implementation of someinterface I use mockito mockery framework
Unfortunately, I can't change the legacy code, and I don't want to add anything statically (for example, to meta - INF)
Is there a simple way to do this test, that is Test at run time?
Solution
You can use powermockito and mockito to simulate 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)); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码