2014-12-05 84 views
0

欲嘲笑其傳遞 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); 
    } 
} 
+0

使用powermock你可以嘲笑靜態方法,但是你可能不應該,除非它是遺留的或不可用於重構代碼。 @Abhish你需要澄清你的問題 – 2014-12-05 07:44:24

+0

我想嘲笑this.rights = WebApplicationContextUtils.getWebApplicationContext(UtilityThreadLocal.getServletContext())。getBean(RoleService.class).get(user.getRoleId())。getRights();但是當我嘗試嘲笑getWebApplicationContext它返回空 – 2014-12-05 07:47:59

回答

0

模擬調用getWebApplicationContext這樣

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

這將使用非嚴格匹配,能夠與任何參數,將返回指定的值調用。您可能會更改其他模擬的設置,以便它們實際匹配參數。

+0

感謝羅馬,但我仍然收到空指針異常 – 2014-12-05 08:38:23

+0

我想模擬enire行WebApplicationContextUtils.getWebApplicationContext(UtilityThreadLocal.getServle tContext())。getBean(RoleService.class).get (user.getRoleId())getRights();返回字符串數組的權限 – 2014-12-05 08:43:13

+0

您不能模擬整行。你可以模擬單個電話。但是你顯示的測試試圖做到這一點,即分別模擬該行中的每個呼叫。你得到的問題是由不正確的嘲笑造成的,其中一個模擬不起作用(由於輸入參數不正確,我猜),所以這就是我寫上一個建議的原因。在這種情況下,easymock返回空值。在測試下調試您的代碼,並查找哪個方法調用返回null。這將是你應該修復的不正確的模擬方法。 – 2014-12-05 14:46:07