有哪些方法可以测试依赖于静态方法的方法? [英] What are ways to test methods that depend on static methods?

查看:88
本文介绍了有哪些方法可以测试依赖于静态方法的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试一些依赖于Spring Security的安全相关类。此代码使用 SecurityContextHolder.getContext()这是静态的。如何在不设置整个安全上下文的情况下测试调用方法?

I need to test some security related classes that depend on Spring Security. This code makes use of SecurityContextHolder.getContext() which is static. How can I test the calling method without setting up an entire security context?

我们正在使用JUnit 4和Mockito。 Mockito在常见问题解答中非常清楚,静态方法不受支持。还有其他选择吗? Spring Security案例的答案很好,但我正在寻找更普遍问题的解决方案。

We are using JUnit 4 with Mockito. Mockito was pretty explicit in it's FAQ that static methods where not supported. Is there an alternative? An answer for the Spring Security case would be nice, but I am looking for a solution to the more general problem.

推荐答案

有看看 PowerMock ,它将允许你模拟静态方法,构造函数和各种各样的通常你不能用java做的其他疯狂的事情。它集成了大多数模拟库,包括mockito(在这里查看 http://code.google.com/ p / powermock / wiki / MockitoUsage13 示例)。

Have a look at PowerMock it will allow you to mock out static method, constructors and do all sorts of other crazy things you wouldn't normally be able to do with java. It integrates with most mocking libraries including mockito (look here http://code.google.com/p/powermock/wiki/MockitoUsage13 for an example).

一般来说,我发现这是一个非常有用的库,可以放在测试工具箱中(编写java时)。唯一需要注意的是,由于这个库会使用你的字节码,如果你有其他库进行字节码检测/操作,你可能会遇到麻烦,但是在你尝试之前你不会知道。

In general I've found this to be a very useful library to have in your testing toolbox (when coding java). The only caveat is that since this library plays around with your bytecode, if you have other libraries that do bytecode instrumentation/manipulation you can run into trouble, but you won't know until you try.

这篇关于有哪些方法可以测试依赖于静态方法的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆