2013-03-18 139 views
1
private ServiceImpl() { 
    // TODO Auto-generated constructor stub 

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

我想模拟这个方法,这是一个私有构造函数,它正在初始化springContext。我使用beans.xml来设置beanfactory,通过我的powermockito测试用例,我已经指定了bean和它的类名。仍然这种方法无法获得reManager的实例。如何模拟springcontext?

+1

你想达到什么目的?因为如果你想获得一个Spring bean的实例来在测试中使用它,Spring提供了测试支持,可以让你做到这一点。您可以通过AbstractJUnit4SpringContextTests类和@ContextConfiguration注释在测试中创建一个Spring上下文。我可以为你提供一个例子,如果这你肯定要找 – pvm14 2013-03-18 14:08:57

+0

。我正在寻找使用powermockito进行测试。你能举个例子吗? – user2181531 2013-03-18 14:16:39

+0

@ pvm14:如果你也给我一些有用的链接,那就太好了 – user2181531 2013-03-18 14:20:11

回答

1

如果你想做的是在你的一个测试中创建一个Spring bean的实例,你不需要使用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 
} 

}

beans.xml文件中,可以定义你的应用程序上下文文件。我能想到的最好的链接权所知道的是

Spring Testing Support

+0

您可以放弃'@ Before' - 因为这将在每个测试中执行 - 并且只需在'reManager'字段上粘贴'@ Autowired'。 :-) – Jonathan 2013-03-18 14:51:15

+0

是的,你是绝对正确的我只是想用问题中出现的元素给出答案 – pvm14 2013-03-18 14:57:42

2

原谅我,如果我误解的东西,但如果你使用PowerMockito不能做你的线沿线的东西:

@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... 
    } 
} 

查看更多信息here关于如何验证静态行为。

或者......我会改变设计,使你的依赖是传递给类测试,如:

@Test 
public void foo() { 
    final ReManager manager = Mockito.mock(ReManager.class); 
    final ServiceImpl service = new ServiceImpl(manager); 

    ... etc... 
} 

那就没有必要PowerMock,你的测试变得更容易,有少之间的耦合类。

+0

据我所知,类'SpringContext'不存在,并且等价的右边的ApplicationContext没有静态'getBean'方法。那么告诉我你需要什么静态测试? ;-) – pvm14 2013-03-18 14:54:05

+0

@ pvm14我假设'SpringContext'是一个由提问者创建的类...我个人会让Spring为我注入所有的依赖关系。原则上我同意你的意见! :-) – Jonathan 2013-03-18 14:58:21

+0

你赢了;-)。像往常一样,你的绝对正确,我的阅读障碍再次愚弄我,我没有注意到在这个问题 – pvm14 2013-03-18 15:09:17