c# - 使用 Hangfire 对 MVC 应用进行单元测试

标签 c# unit-testing asp.net-mvc-3

您好,我正在尝试使用 OWin 为使用 Hangfire 的 MVC 3 Controller 设置单元测试。正常操作下,Hangfire 在主 Controller 的配置功能中进行配置,如下所示

public void Configuration(IAppBuilder app)
{
    var sCon = ConnectionString.GetConnectionString();
    try
    {
        IUnitOfWork oUoW = UnitOfWorkFactory.GetInstance(sCon);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
        return;
    }
    app.UseHangfire(config =>
    {
        config.UseSqlServerStorage(ConnectionString.GetConnectionString());
        config.UseServer();
    });
}

我正在像这样使用 Moq 设置 HttpContextBase

private static HttpContextBase FakeAuthenticatedHttpContext()
{
    var context = new Mock<HttpContextBase>();
    var request = new Mock<HttpRequestBase>();
    var response = new Mock<HttpResponseBase>();
    var session = new Mock<HttpSessionStateBase>();
    var server = new Mock<HttpServerUtilityBase>();
    var user = new Mock<IPrincipal>();
    var identity = new Mock<IIdentity>();
    var application = new Mock<HttpApplicationStateBase>();

    context.Setup(ctx => ctx.Request).Returns(request.Object);
    context.Setup(ctx => ctx.Response).Returns(response.Object);
    context.Setup(ctx => ctx.Session).Returns(session.Object);
    context.Setup(ctx => ctx.Server).Returns(server.Object);
    context.Setup(ctx => ctx.User).Returns(user.Object);
    context.Setup(ctx => ctx.Application).Returns(application.Object);
    user.Setup(ctx => ctx.Identity).Returns(identity.Object);
    identity.Setup(id => id.IsAuthenticated).Returns(true);
    identity.Setup(id => id.Name).Returns("admin");

    return context.Object;
}

moBaseController.SetFakeAuthenticatedControllerContext();

如何伪造对配置的调用来设置作业存储?我一直在查看 Hangfire 文档,他们在这方面有点神秘,并提到作业存储应该像这样设置

GlobalConfiguration.Configuration.UseSqlServerStorage("<connection string or its name>");
using (new BackgroundJobServer())
{
   BackgroundJob.Enqueue(() => ProcessReport(oReportRequest, JobCancellationToken.Null)));

}

但是 GlobalConfiguration 在 Controller 或单元测试中的任何地方都是未知的。

我使用的是 Hangfire 版本 1.1.1 和 OWin 2.1。

总而言之,我正在寻找一种方法来模拟 MVC 3 方法调用的环境,以透明地设置作业存储和后台服务器。即我如何模拟 Controller ,以便在调用该方法时已设置该 Controller 。

这通常是我在单元测试中调用 Controller 的方式:

oViewResult = (ViewResult)moController.RunExport(oRequest);

Assert.IsNotNull(oViewResult, "Didn't return a view result!");
Assert.IsTrue(oViewResult.ViewName == "RunReport", "Didn't return a valid view name!");
Assert.IsTrue(oViewResult.Model != null, "No Model response!");

var oResult = (string)oViewResult.Model;
Assert.IsTrue(oResult == "Ok", "Export did not run as expected!");

一般来说,当调用 Hangfire 时,它​​在 Controller 中是这样完成的

oTokens.Add(oReportStatus.ID, BackgroundJob.Enqueue(() => ProcessReport(oReportRequest, JobCancellationToken.Null)));

最佳答案

将此作为解决方案,根据@Rob的建议,我将所有BackgroundJob.Enqueue()引用更改为IBackgroundJobClient bjc = GetJobClient(); bjc.Enqueue(...);并 mock IBackgroundJobClient,并且能够以这种方式进行测试。

关于c# - 使用 Hangfire 对 MVC 应用进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126979/

相关文章:

asp.net-mvc-3 - MvcSiteMapProvider 和 web.config : Parser Error Message: Value cannot be null

jquery - Css 和 Jquery 在对话框中无法正常工作

c# - 多次调用 SuppressFinalize

c# - 为什么这个 ThreadPool.QueueUserWorkItem 代码没有让我的测试失败?

c# - 在 C# 中区分 Click 和 DoubleClick 事件

ios - Swift 单元测试错误 - 找不到架构 i386 的 AWSCore 框架

iphone - iPhone 旋转单元测试

c# - 在 datagridview 中更新日期格式时出现错误

javascript - 如何对调用自身的函数进行单元测试

c# - 我可以(或应该)在 Controller 中使用 ActionLink()