[英]How to mock static method available in abstract class which returns servlet context using spring based unit test
I want to mock static method which passes UtilityThreadLocal.getServletContext()
as a parameter to webApplicationContextUtils.getWebApplicationContext (UtilityThreadLocal.getServletContext())).
我想模拟将UtilityThreadLocal.getServletContext()
作为参数传递给webApplicationContextUtils.getWebApplicationContext (UtilityThreadLocal.getServletContext())).
静态方法webApplicationContextUtils.getWebApplicationContext (UtilityThreadLocal.getServletContext())).
I want to use easy mock + powermock. 我想使用简单的模拟+ powermock。 I am probaly tring to create mock from xml and autowring those in my test class but not able to do such. 我可能正在尝试从xml创建模拟并将我测试类中的那些自动生成,但无法做到这一点。 Here is my code which is not working properly. 这是我的代码,无法正常工作。 It returning Null pointer exception
and sometime Illegal state exception 它返回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);
}
}
Mock the call to getWebApplicationContext
like this 像这样模拟对getWebApplicationContext
的调用
expect(WebApplicationContextUtils.getWebApplicationContext(
EasyMock.anyObject(ServletContext.class)))
.andReturn(webAppContextMock);
This uses non strict matching that is call with any parameter will return specified value. 这使用非严格匹配,即使用任何参数调用都会返回指定值。 You may probably change setup of other mocks so that they actually match the parameters. 您可能会更改其他模拟的设置,以使它们实际上与参数匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.