2013-10-22 60 views
0

我正在進行Junit測試,在這裏我需要一起處理Easymock和Class對象來擦測試。使用簡單模擬對象

以下是我的代碼片斷

@Before 
public void setUp() { 
    request=EasyMock.createMock(SlingHttpServletRequest.class); 
    response=EasyMock.createMock(SlingHttpServletResponse.class); 

} 

@Test 
public void testImage() { 

RequestContext ctx = new RequestContext(); 

// RequestContext and RequestContext Util are both classes defined in Project 

    expect(RequestContextUtil.setupContext(request,response)).andReturn(ctx); 

    // This line is throwing an error , so I am not able to add replay or verify method 

} 

我想看到一個例子,我可以使用簡易模擬和類對象在一起,我無法找到適合我的情況。任何人都可以指點我一個例子嗎?

+1

你正在嘗試做是行不通的,因爲你的代碼不使用模擬但不能嘲笑一個靜態方法的調用(因爲它不叫上一個模擬)。如果您提供更多的上下文,您想要測試什麼以及如何測試,也許有人可以幫助您找到解決方法。 –

+0

我有一個Util類,用於存儲應用程序的請求上下文和其他一組屬性相關的。 Util類使用slingrequest和sling響應對象。我試圖在這個Util類(它的一個方法)上創建一個junit測試。 – KAPILP

+1

沒有看到整個代碼很難給你任何建議,但你可能不得不停止使用mock並正確設置所有東西,或者重構你的代碼庫,這樣你就可以使用mock。 –

回答

1

您無法使用EasyMock模擬靜態方法調用。 2個解決方案:

  • 提取靜態調用到您的SUT不同的方法和測試SUT的部分嘲笑版本(嘲諷只有在靜態調用完成後,新方法)。 Partial mocks using easymock
  • 正如上面提到的那樣,使用PowerMock並直接模擬靜態調用。
5
private MockHttpServletRequest request; 
private MockHttpServletResponse response; 

@Before 
public void setup() { 
    request = new MockHttpServletRequest(); 
    response = new MockHttpServletResponse(); 
} 

    @Test 
    public void testImage() { 
     //here you don't need to `expect` or `reply` 

    // `request` and `response` is mock now. 
    }