使用PowerMockito 1.6验证静态方法调用

编程入门 行业动态 更新时间:2024-10-26 08:21:05
本文介绍了使用PowerMockito 1.6验证静态方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在为类似下面给出的示例的方法编写JUnit测试用例:

I am writing JUnit test case for methods similar to sample given below:

Class SampleA{ public static void methodA(){ boolean isSuccessful = methodB(); if(isSuccessful){ SampleB.methodC(); } } public static boolean methodB(){ //some logic return true; } } Class SampleB{ public static void methodC(){ return; } }

我在我的测试类中编写了以下测试用例:

I wrote the following test case in my test class:

@Test public void testMethodA_1(){ PowerMockito.mockStatic(SampleA.class,SampleB.class); PowerMockito.when(SampleA.methodB()).thenReturn(true); PowerMockito.doNothing().when(SampleB.class,"methodC"); PowerMockito.doCallRealMethod().when(SampleA.class,"methodA"); SampleA.methodA(); }

现在我要验证是否调用类Sample B的静态methodC()或不。如何使用PowerMockito 1.6实现?我尝试了很多东西,但似乎并没有为我做好准备。任何帮助都表示赞赏。

Now I want to verify whether static methodC() of class Sample B is called or not. How can I achieve using PowerMockito 1.6? I have tried many things but it doesn't seems to be working out for me. Any help is appreciated.

推荐答案

就个人而言,我不得不说PowerMock等解决了你不应该解决的问题。如果你的代码不错,那就没有了。在某些情况下,它是必需的,因为框架等使用静态方法导致代码无法以其他方式测试,但如果它是关于您的代码,您应该总是更喜欢重构而不是静态模拟。

Personally, I have to say that PowerMock, etc. is the solution to a problem that you shouldn't have if your code wasn't bad. In some cases, it is required because frameworks, etc. use static methods that lead to code that simply cannot be tested otherwise, but if it's about YOUR code, you should always prefer refactoring instead of static mocking.

无论如何,在PowerMockito中验证不应该那么难......

Anyway, verifing that in PowerMockito shouldn't be that hard...

PowerMockito.verifyStatic( Mockito.times(1)); // Verify that the following mock method was called exactly 1 time SampleB.methodC();

(当然,为了实现这个目的,你必须将SampleB添加到 @ PrepareForTest 注释并为其调用 mockStatic 。)

(Of course, for this to work you must add SampleB to the @PrepareForTest annotation and call mockStatic for it.)

更多推荐

使用PowerMockito 1.6验证静态方法调用

本文发布于:2023-10-31 07:13:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545398.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   方法   PowerMockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!