2012-10-18 27 views
20

我有一個查找查詢參數,並返回一個布爾值的函數:如何模擬HttpServletRequest?

public static Boolean getBooleanFromRequest(HttpServletRequest request, String key) { 
     Boolean keyValue = false; 
     if(request.getParameter(key) != null) { 
      String value = request.getParameter(key); 
      if(keyValue == null) { 
       keyValue = false; 
      } 
      else { 
       if(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("1")) { 
        keyValue = true; 
       } 
      } 
     } 
     return keyValue; 
    } 

我都JUnit和EasyMock的在我的pom.xml中,我該如何去嘲諷HttpServletRequest的?

+3

下面的回答這個問題,因爲寫得好,但我通常會主張重構代碼,使大多數非平凡的邏輯處於更適當的抽象層次。如果可能的話,那麼嘲笑HttpServletRequest就變得沒有必要了。 –

回答

8

HttpServletRequest的很像是任何其他接口,這樣你就可以按照EasyMock Readme

這裏嘲笑它是如何單元測試getBooleanFromRequest方法

// static import allows for more concise code (createMock etc.) 
import static org.easymock.EasyMock.*; 

// other imports omitted 

public class MyServletMock 
{ 
    @Test 
    public void test1() 
    { 
     // Step 1 - create the mock object 
     HttpServletRequest req = createMock(HttpServletRequest.class); 

     // Step 2 - record the expected behavior 

     // to test true, expect to be called with "param1" and if so return true 
     // Note that the method under test calls getParameter twice (really 
     // necessary?) so we must relax the restriction and program the mock 
     // to allow this call either once or twice 
     expect(req.getParameter("param1")).andReturn("true").times(1, 2); 

     // program the mock to return false for param2 
     expect(req.getParameter("param2")).andReturn("false").times(1, 2); 

     // switch the mock to replay state 
     replay(req); 

     // now run the test. The method will call getParameter twice 
     Boolean bool1 = getBooleanFromRequest(req, "param1"); 
     assertTrue(bool1); 
     Boolean bool2 = getBooleanFromRequest(req, "param2"); 
     assertFalse(bool2); 

     // call one more time to watch test fail, just to liven things up 
     // call was not programmed in the record phase so test blows up 
     getBooleanFromRequest(req, "bogus"); 

    } 
} 
12

使用一些模擬框架,例如MockitoJMock,它具有嘲笑這些對象的能力。

在的Mockito,你可以做嘲諷爲:

HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class); 

有關詳細的Mockito,請參閱:How do I drink it?在現場的Mockito。

在JMock的,你可以做嘲諷爲:

Mockery context = new Mockery(); 
HttpServletRequest mockedRequest = context.mock(HttpServletRequest.class); 

有關JMock的詳細信息,請參閱:jMock - Getting Started

+0

爲什麼不需要強制轉換? –

+0

因爲他們使用類型推斷的泛型,就像任何好的現代圖書館應該那樣。 – Hiro2k

+0

您將'.class'作爲參數傳遞給模擬方法。 –