69

所以控制器上下文取决于一些 asp.net 内部。有哪些方法可以干净地模拟这些以进行单元测试?当我只需要例如 Request.HttpMethod 返回“GET”时,似乎很容易用大量设置阻塞测试。

我在网上看到了一些例子/助手,但有些已经过时了。认为这将是保持最新和最伟大的好地方。

我正在使用最新版本的 rhino mocks

4

7 回答 7

65

使用 MoQ,它看起来像这样:

var request = new Mock<HttpRequestBase>();
request.Expect(r => r.HttpMethod).Returns("GET");
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(request.Object);
var controllerContext = new ControllerContext(mockHttpContext.Object
, new RouteData(), new Mock<ControllerBase>().Object);

我认为 Rhino Mocks 的语法是相似的。

于 2008-08-28T16:06:37.890 回答
21

这是一个使用 MsTest 和 Moq 模拟 HttpRequest 和 HttpResponse 对象的示例单元测试类。(.NET 4.0,ASP.NET MVC 3.0)

控制器操作从请求中获取值并在响应对象中设置 http 标头。可以用类似的方式模拟其他 http 上下文对象

[TestClass]
public class MyControllerTest
{
    protected Mock<HttpContextBase> HttpContextBaseMock;
    protected Mock<HttpRequestBase> HttpRequestMock;
    protected Mock<HttpResponseBase> HttpResponseMock;

    [TestInitialize]
    public void TestInitialize()
    {
        HttpContextBaseMock = new Mock<HttpContextBase>();
        HttpRequestMock = new Mock<HttpRequestBase>();
        HttpResponseMock = new Mock<HttpResponseBase>();
        HttpContextBaseMock.SetupGet(x => x.Request).Returns(HttpRequestMock.Object);
        HttpContextBaseMock.SetupGet(x => x.Response).Returns(HttpResponseMock.Object);
    }

    protected MyController SetupController()
    {
        var routes = new RouteCollection();
        var controller = new MyController();
        controller.ControllerContext = new ControllerContext(HttpContextBaseMock.Object, new RouteData(), controller);
        controller.Url = new UrlHelper(new RequestContext(HttpContextBaseMock.Object, new RouteData()), routes);
        return controller;
    }

    [TestMethod]
    public void IndexTest()
    {
        HttpRequestMock.Setup(x => x["x"]).Returns("1");
        HttpResponseMock.Setup(x => x.AddHeader("name", "value"));

        var controller = SetupController();
        var result = controller.Index();
        Assert.AreEqual("1", result.Content);

        HttpRequestMock.VerifyAll();
        HttpResponseMock.VerifyAll();
    }
}

public class MyController : Controller
{
    public ContentResult Index()
    {
        var x = Request["x"];
        Response.AddHeader("name", "value");
        return Content(x);
    }
}
于 2013-02-22T04:37:50.547 回答
19

这是 Jason 链接的片段。它与菲尔的方法相同,但使用犀牛。

注意:mockHttpContext.Request 在mockRequest 的内部被存根之前被存根返回 mockRequest 。我相信这个命令是必需的。

// create a fake web context
var mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
var mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
mockHttpContext.Stub(x => x.Request).Return(mockRequest);

// tell the mock to return "GET" when HttpMethod is called
mockRequest.Stub(x => x.HttpMethod).Return("GET");            

var controller = new AccountController();

// assign the fake context
var context = new ControllerContext(mockHttpContext, 
                  new RouteData(), 
                  controller);
controller.ControllerContext = context;

// act
...
于 2008-08-29T01:53:09.167 回答
10

这个过程在 MVC2 中似乎略有改变(我使用的是 RC1)。[HttpPost]如果操作需要特定方法 ( , [HttpGet]) , Phil Haack 的解决方案对我不起作用。在 Reflector 中探索,看起来验证这些属性的方法已经改变。MVC 现在检查request.Headersrequest.Formrequest.QueryStringX-HTTP-Method-Override值。

如果为这些属性添加模拟,它会起作用:

var request = new Mock<HttpRequestBase>();
request.Setup(r => r.HttpMethod).Returns("POST");
request.Setup(r => r.Headers).Returns(new NameValueCollection());
request.Setup(r => r.Form).Returns(new NameValueCollection());
request.Setup(r => r.QueryString).Returns(new NameValueCollection());

var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(request.Object);
var controllerContext = new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
于 2009-12-24T17:15:35.903 回答
6

或者你可以使用 Typemock Isolator 来做到这一点,根本不需要发送一个假控制器:

Isolate.WhenCalled(()=>HttpContext.Request.HttpMethod).WillReturn("Get");
于 2009-01-29T14:29:07.287 回答
2

我已经完成了这个规范

public abstract class Specification <C> where C: Controller
{
    protected C controller;

    HttpContextBase mockHttpContext;
    HttpRequestBase mockRequest;

    protected Exception ExceptionThrown { get; private set; }

    [SetUp]
    public void Setup()
    {
        mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
        mockRequest = MockRepository.GenerateMock<HttpRequestBase>();

        mockHttpContext.Stub(x => x.Request).Return(mockRequest);
        mockRequest.Stub(x => x.HttpMethod).Return("GET");


        EstablishContext();
        SetHttpContext();

        try
        {
            When();
        }
        catch (Exception exc)
        {
            ExceptionThrown = exc;
        }
    }

    protected void SetHttpContext()
    {
        var context = new ControllerContext(mockHttpContext, new RouteData(), controller);
        controller.ControllerContext = context;
    }

    protected T Mock<T>() where T: class
    {
        return MockRepository.GenerateMock<T>();
    }

    protected abstract void EstablishContext();
    protected abstract void When();

    [TearDown]
    public virtual void TearDown()
    {
    }
} 

果汁就在这里

[TestFixture]
public class When_invoking_ManageUsersControllers_Update :Specification   <ManageUsersController>
{
    private IUserRepository userRepository;
    FormCollection form;

    ActionResult result;
    User retUser;

    protected override void EstablishContext()
    {
        userRepository = Mock<IUserRepository>();
        controller = new ManageUsersController(userRepository);

        retUser = new User();
        userRepository.Expect(x => x.GetById(5)).Return(retUser);
        userRepository.Expect(x => x.Update(retUser));

        form = new FormCollection();
        form["IdUser"] = 5.ToString();
        form["Name"] = 5.ToString();
        form["Surename"] = 5.ToString();
        form["Login"] = 5.ToString();
        form["Password"] = 5.ToString();
    }

    protected override void When()
    {
        result = controller.Edit(5, form);
    }

    [Test]
    public void is_retrieved_before_update_original_user()
    {
        userRepository.AssertWasCalled(x => x.GetById(5));
        userRepository.AssertWasCalled(x => x.Update(retUser));
    }
}

请享用

于 2008-10-20T22:04:51.953 回答
0

我发现长时间的嘲笑程序摩擦太大。

我们发现的最好的方法——在一个真实的项目中使用 ASP.NET MVC——是将 HttpContext 抽象为一个简单地通过的 IWebContext 接口。然后你可以毫不费力地模拟 IWebContext 。

这是一个例子

于 2008-08-28T23:01:25.523 回答