Java 如何模拟springcontext?

Java 如何模拟springcontext?,java,junit,mockito,powermock,Java,Junit,Mockito,Powermock,我想模拟这个方法,这是一个私有构造函数,它正在初始化springContext。我正在使用beans.xml通过powermockito测试用例设置beanfactory,在这里我指定了bean及其类名。但是,该方法仍然无法获取Remager的实例。如果您想在某个测试中创建Springbean的实例,则不需要使用powermockito。你可以这样做 private ServiceImpl() { // TODO Auto-generated constructor stub

我想模拟这个方法,这是一个私有构造函数,它正在初始化springContext。我正在使用beans.xml通过powermockito测试用例设置beanfactory,在这里我指定了bean及其类名。但是,该方法仍然无法获取Remager的实例。

如果您想在某个测试中创建Springbean的实例,则不需要使用powermockito。你可以这样做

private ServiceImpl() {
    // TODO Auto-generated constructor stub

    reMgr = (ReManager) SpringContext.getBean("reManager");
}

xml是定义应用程序上下文的文件。我认为最好的链接就是这个


如果我有误解,请原谅,但是如果您使用PowerMockito,您不能按照以下方式执行操作:

@ContextConfiguration(locations = "/beans.xml")
public class YourTestJUnit4ContextTest extends  AbstractJUnit4SpringContextTests {

private ReManager reManager;

@Before
public void init() {
    reManager= (ReManager) applicationContext.getBean("reManager");
}

@Test
public void testReManager() {
    // Write here the code for what you wnat to test
}
请参阅有关如何验证静态行为的更多信息

或者。。。我会更改设计,以便将依赖项传递给被测类,例如:

@RunWith(PowerMockRunner.class)
@PrepareForTest(SpringContext.class) 
public FooTest {    
    @Test
    public void foo() {
        final ReManager manager = Mockito.mock(ReManager.class);

        PowerMockito.mockStatic(SpringContext.class);
        Mockito.when(SpringContext.getBean("reManager")).thenReturn(manager);

        ... etc...
    }
}

这样就不需要PowerMock,您的测试变得更容易,类之间的耦合也更少。

您想要实现什么?因为如果您想让Springbean的一个实例在测试中使用它,Spring提供了测试支持,使您能够完全做到这一点。您可以通过AbstractJUnit4SpringContextTests类和@ContextConfiguration注释在测试中创建Spring上下文。我可以给你举个例子,如果这就是你想要的。我希望使用powermockito进行测试。你能给我举个例子吗?@pvm14:如果你能给我一些有用的链接,那就太好了。我会修改它,这样你就可以把
ReManager
的一个实例传递到
serviceinpl
,这样测试就容易多了!您可以将
@放在
@之前,因为每次测试都会执行该操作,只需将
@Autowired
粘贴到
Remanger
字段即可。:-)是的,你完全正确,我只是想用问题中已经出现的元素给出一个答案,据我所知,类“SpringContext”不存在,并且等效的right one ApplicationContext没有任何静态的“getBean”方法。那么,请告诉我,您需要在这里进行静态测试的目的是什么?;-)@pvm14我假设
SpringContext
是一个由提问者创建的类。。。就我个人而言,我会让Spring为我注入所有依赖项。我原则上同意你的意见!:-)你赢了;-)。你完全正确,像往常一样,我的诵读困难再次愚弄了我,我没有注意到SpringContext.getBean在问题中我这里有一个问题,我们可以多次使用PrepareForest吗,因为我已经在类级别上进行了PrivateMethodVerification,我可以为静态添加这两个吗?我找不到验证包下的static.class?包裹是什么path@user2181531您可以指定要准备的多个类,例如
@PrepareForTest({X.class,Y.class})
。看一看完整的例子,包等。。。我希望这有帮助。
@Test
public void foo() {
    final ReManager manager = Mockito.mock(ReManager.class);
    final ServiceImpl service = new ServiceImpl(manager);

    ... etc...
}