问题描述
我有一个单元测试问题,其中的一个类有一个静态变量想要加载Spring Application Ctx.
I have a Unit testing problem where a class has a static variable which wants to load the Spring Application Ctx.
此类并非来自Bean Factory,并且我无法更改此事实.
static ApplicationContext applicationContext = ...;
这很好用,但是很难 JMock ,或者至少我不知道一种方法,直到Spring Ctx想要启动为止.对于单元测试情况不是很理想.
This works fine, but is hard to JMock, or atleast I don't know a way and until I can the Spring Ctx wants to start up. Not ideal for a unit test situation.
有没有人知道的解决方法?我可以选择将static变量更改为所需的任何内容.
Is there a work around that anyone knows?I have the option to change the static variable to anything I wish..
谢谢.
推荐答案
我自己解决了这个问题.
Solved this myself.
最后真的很简单.只是需要将我的静态函数包装在一个我可以模拟的类中.
Was really simple in the end. Justed need to wrap my static in a class which I could then mock.
public class ApplicationContextHolder implements ApplicationContextHoldable {
protected static ApplicationContext applicationContext = ...;
@Override
public ApplicationContext getApplicationContext() {
return ApplicationContextHolder.applicationContext;
}
}
这篇关于如何使用JMock在Java中模拟静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!