如何模拟抽象类中可用的静态方法,该方法使用基于spring的单元测试返回servlet上下文

时间:2014-12-05 07:38:48

标签: java junit powermock easymock

我想模拟传递的静态方法 UtilityThreadLocal.getServletContext()作为webApplicationContextUtils.getWebApplicationContext (UtilityThreadLocal.getServletContext())).

的参数

我想使用easy mock + powermock。我很可能要从xml创建mock并在我的测试类中自动生成但不能这样做。这是我的代码无法正常工作。它返回Null pointer exception,有时非法状态异常

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@PrepareForTest({
    WebApplicationContextUtils.class
})
public class LoginServiceTest {
    @Rule
    public PowerMockRule rule = new PowerMockRule();
    @Autowired
    private LoginService loginService;

    @Test
    public void loginTest() throws Exception {
        String[] rights = new String[] {
        "MANAGE_TENANTS", "MANAGE_USERS", "MANAGE_APPLICATIONS", "MANAGE_SETTINGS", "MANAGE_HISTORY", "MANAGE_OFFICES", "EXPORT_TIMESHEETS", "MANAGE_POLICIES", "MANAGE_ASSETS", "MANAGE_LEAVES"
        };
        Role roleObj = new Role();
        roleObj.setRights(rights);
        WebApplicationContext webAppContextMock = createNiceMock(WebApplicationContext.class);
        RoleService roleServiceBeanMock = createNiceMock(RoleService.class);
        PowerMock.mockStatic(WebApplicationContextUtils.class);
        expect(WebApplicationContextUtils.getWebApplicationContext(UtilityThreadLocal.getServletContext())).andReturn(webAppContextMock);
        expect(webAppContextMock.getBean(RoleService.class)).andReturn(roleServiceBeanMock);
        expect(roleServiceBeanMock.get((long) 2).getRights()).andReturn(rights);
        expect(roleObj.getRights()).andReturn(roleObj.getRights());
        PowerMock.replay(WebApplicationContextUtils.class);
        replay(webAppContextMock);
        replay(roleServiceBeanMock);
    }
}

1 个答案:

答案 0 :(得分:0)

将调用模拟为getWebApplicationContext

expect(WebApplicationContextUtils.getWebApplicationContext(
           EasyMock.anyObject(ServletContext.class)))
   .andReturn(webAppContextMock);

这使用非严格匹配,任何参数调用都将返回指定值。您可能可能会更改其他模拟的设置,以便它们实际匹配参数。