我已經爲HttpSession創建了一個模擬對象,如下所示。EasyMock Void方法對象哈希碼不匹配
HttpSession mocks.createMock(HttpSession.class);
現在我正在測試一些方法,該方法是
public String validateProduct(String productId,Model model,HttpServletRequest request){
Customer customer=new Customer();
Product product=customerService.validateProduct(productId, VSCConstants.CLIENT_CODE);
customer.setProduct(product);
/*Doing more operation with customer*/
request.getSession().setAttribute(
VSCConstants.SESSION_CUSTOMER,customer);
request.setAttribute("response", "InValidVIN");
return "forward:/profile";
}
現在對於我的JUnit測試代碼是
expect(customerService.validateProduct(null, VSCConstants.CLIENT_CODE))
.andReturn(new Product());
expect(request.getSession()).andReturn(session).anyTimes();
session.setAttribute(VSCConstants.SESSION_CUSTOMER, createdObject);
expectLastCall().andAnswer(new IAnswer<Customer>() {
public Customer answer() throws Throwable {
createdObject= (Customer) EasyMock.getCurrentArguments()[1];
return null;
}
});
現在的問題是因爲session.setAttribute()
方法是無效的方法,以我已經使用 expectLastCall(),但如果你看到我正在測試的方法是創建一個新的客戶並將其添加到會話中,所以在這裏它變得不匹配,我正在流動異常。
Unexpected method call HttpSession.setAttribute("SESSION_CUSTOMER", [email protected]):
HttpSession.setAttribute("SESSION_CUSTOMER", null): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:85)
at $Proxy6.setAttribute(Unknown Source)
at com.budco.vsc.mvc.controller.AdvancedCustomerSearchController.validateProduct(AdvancedCustomerSearchController.java:110)
at com.budco.vsc.mvc.controller.AdvancedCustomerSearchController.getAdvancedSearchResult(AdvancedCustomerSearchController.java:83)
at com.budco.vsc.mvc.controller.AdvancedCustomerSearchControllerTest.testgetAdvancedSearchResultWithValidateProduct(AdvancedCustomerSearchControllerTest.java:148)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
秀上.....
我希望,我需要使用相同的客戶對象,它是測試方法中使用,但作爲該方法創建對象這是不可能的。 第二個選項可能會覆蓋hashCode(),但它會很沉重,因爲該方法在客戶上做了很多事情,而且它是一個非常大的對象,滿足了很多其他對象和集合。 有沒有簡單的方法,以便我可以跳過不匹配。
我已經做了,但現在我得到的例外看到我的編輯 – Krushna
session.setAttribute(VSCConstants.SESSION_CUSTOMER,createdObject); 這應該是: session.setAttribute(EasyMock.eq(VSCConstants.SESSION_CUSTOMER),EasyMock.anyObject(Customer.class)); 你沒有句柄Customer對象在這一點上,所以你只要想到類型的任何對象,再後來執行的對象進行斷言,它匹配你期望的一個(或者你更喜歡以斷言)。 –
謝謝你的工作 – Krushna