2011-11-23 52 views
10

如何使用Moq創建一個純存根?隨着犀牛嘲笑我這樣做是這樣的:如何使用Moq創建存根

[TestFixture] 
public class UrlHelperAssetExtensionsTests 
{ 
    private HttpContextBase httpContextBaseStub; 
    private RequestContext requestContext; 
    private UrlHelper urlHelper; 
    private string stylesheetPath = "/Assets/Stylesheets/{0}"; 

    [SetUp] 
    public void SetUp() 
    { 
      httpContextBaseStub = MockRepository.GenerateStub<HttpContextBase>(); 
      requestContext = new RequestContext(httpContextBaseStub, new RouteData()); 
      urlHelper = new UrlHelper(requestContext); 
    } 

    [Test] 
    public void PbeStylesheet_should_return_correct_path_of_stylesheet() 
    { 
     // Arrange 
     string expected = stylesheetPath.FormatWith("stylesheet.css"); 

     // Act 
     string actual = urlHelper.PbeStylesheet(); 

     // Assert 
     Assert.AreEqual(expected, actual); 
    } 
} 

我將如何創建使用起訂量爲MockRepository.GenerateStub<HttpContextBase>();存根?還是應該留在Rhino Mocks?

回答

1
var mockHttpContext = new Mock<HttpContextBase>(); 
+0

我知道有一個存根和模擬的差異,但您的實現創建一個模擬或存根?看起來像對我的模擬? –

+3

命名是指您使用此對象的方式。所以,如果你不會驗證這個對象上的任何東西,它是一個存根,如果你願意的話 - 這是一個模擬。 – BartoszKP

10

這裏是我的建議給你:

Mock<HttpContextBase> mock = new Mock<HttpContextBase>(); 
mock.SetupAllProperties(); 

然後你要做的設置。

如需進一步信息請參閱homepage of the MOQ project.

+0

我需要什麼設置?我只需要在我的代碼中使用它。我不使用httpContextBaseStub任何地方。 –

+0

你必須以這種方式設置它,你的課堂需要它。這取決於你想運行的單元測試。你可以說一般。 – Fischermaen

+0

我已經更新了我的測試。請檢查:) –