欲嘲笑其傳遞 UtilityThreadLocal.getServletContext()
作爲參數來webApplicationContextUtils.getWebApplicationContext (UtilityThreadLocal.getServletContext())).
如何嘲笑使用彈簧基於單元測試
我想使用容易模擬+ powermock靜態方法,它返回servlet上下文抽象類可用的靜態方法。我很可能會從xml創建模擬,並在我的測試類中自動創建它們,但無法做到這一點。這是我的代碼無法正常工作。它返回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);
}
}
使用powermock你可以嘲笑靜態方法,但是你可能不應該,除非它是遺留的或不可用於重構代碼。 @Abhish你需要澄清你的問題 – 2014-12-05 07:44:24
我想嘲笑this.rights = WebApplicationContextUtils.getWebApplicationContext(UtilityThreadLocal.getServletContext())。getBean(RoleService.class).get(user.getRoleId())。getRights();但是當我嘗試嘲笑getWebApplicationContext它返回空 – 2014-12-05 07:47:59