对于带参数的方法,Powermockito doNothing
我用Java开发了一个应用程序,我正在尝试使用Powermockito创建unit testing(我应该补充一点,我是unit testing的新手)。
我有一个名为Resource的类,它有一个名为readResources的静态方法:
public static void readResources(ResourcesElement resourcesElement);
ResourcesElement也由我编码。 在测试中,我想创建自己的资源,所以我希望上面的方法什么都不做。 我尝试使用此代码:
PowerMockito.spy(Resource.class); PowerMockito.doNothing().when(Resource.class, "readResources", Matchers.any(ResourcesElement.class));
unit testing抛出exception:
org.mockito.exceptions.misusing.UnfinishedStubbingException:此处检测到未完成的存根: – > at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
Powermockito还建议我应该使用thenReturn或者之后使用Thhrow,但似乎’when’方法在doNothing之后调用时返回void(这是合乎逻辑的)。 如果我尝试:
PowerMockito.when(Resource.class, "readResources", Matchers.any(ResourcesElement.class)).....
什么时候什么都不是一个选择。
我设法使用方法的2个参数版本创建没有参数的方法,什么都不做。 例如:
PowerMockito.doNothing().when(Moduler.class, "startProcessing");
这工作(startProcessing不接受任何参数)。
但是,我怎样才能制定出与Powermockito无关的方法呢?
您可以在下面找到function齐全的示例。 由于你没有发布完整的例子,我只能假设你没有使用@RunWith
或@PrepareForTest
注释测试类,因为其余的似乎没问题。
@RunWith(PowerMockRunner.class) @PrepareForTest({Resource.class}) public class MockingTest{ @Test public void shouldMockVoidStaticMethod() throws Exception { PowerMockito.spy(Resource.class); PowerMockito.doNothing().when(Resource.class, "readResources", Mockito.any(String.class)); //no exception heeeeere! Resource.readResources("whatever"); PowerMockito.verifyStatic(); Resource.readResources("whatever"); } } class Resource { public static void readResources(String someArgument) { throw new UnsupportedOperationException("meh!"); } }
如果doNothing()
不起作用,你可以使用PowerMockito.doAnswer()
稍微破解它。 这允许你模拟应该做某些事情的void方法,比如设置值等。如果doNothing()
不起作用,使用空白的doAnswer()
应该可以正常工作。
例:
PowerMockito.doAnswer(new org.mockito.stubbing.Answer
为什么要经历这么多麻烦只是为了让你的方法什么都不做。 只需调用PowerMockito.mockStatic(Resource.class)
可以用默认存根替换类中的所有静态方法,这基本上意味着它们什么都不做。
除非您确实想要改变方法的行为以实际执行某些操作,只需调用PowerMockito.mockStatic(Resource.class)
就足够了。 当然,这也意味着类中的所有静态方法都需要考虑。
也许我不能解决你的问题,但我认为有必要指明必须做什么方法,所以如果你没有指定thenReturn或者然后或者什么powerMockito不知道在阅读你的真实代码时需要做什么,例如:
真实代码:
IPager pag; IPagerData> dpag; pag = new PagerImpl(); pag.setFiles(nombrefilesPaginador); pag.setInici(1); dpag = gptService.obtenirDeutes(idSubjecte, idEns, tipusDeute, periode, pag);
通过mockito测试实际代码:
IPager pag = new PagerImpl(); pag.setInici(1); pag.setFiles(0); when(serveiGpt.obtenirDeutes(eq(331225L), eq(IConstantsIdentificadors.ID_ENS_BASE), Matchers.any(ETipusDeute.class), Matchers.any(EPeriodeDeute.class), eq(pag))) .thenThrow(new NullPointerException(" Null!"));
如果没有指定返回,我的测试将失败。 我希望它有所帮助。