单元测试NService.Send从API控制器

时间:2016-08-17 19:04:43

标签: unit-testing nservicebus nsubstitute

我有一个API控制器,它使用NServiceBus发布命令。我正在使用NUnit和NSubstitute进行测试。我想测试模型中的某些属性是否填充在命令

这是我的控制器有路线。

[RoutePrefix("api/fileService")]
public class FileServiceController : ApiController
{
    [HttpPost]
    [Route("releasefile")]
    public async Task<IHttpActionResult> ReleaseFile(FileReleaseAPIModels.ReleaseFileModel model)
    {
        var currentUser = RequestContext.Principal?.Identity as ClaimsIdentity;


        if (model.FileType.Equals("ProductFile"))
        {
            _logger.Info($"Releasing Product files for date: {model.FileDate.ToShortDateString()} ");
            _bus.Send<IReleaseProductFiles>("FileManager.Service", t =>
            {
                t.FileId = Guid.NewGuid();
                t.RequestedDataDate = model.FileDate;
                t.RequestingUser = currentUser?.Name;
                t.RequestDateTime = DateTime.Now;
            });
        }
        return Ok();
    }

}

在我的测试中,我替换(模拟)Ibus并尝试验证收到的呼叫。这是测试方法:

    [Test]
    public async Task TestReleaseProductsFile()
    {
        var bus = Substitute.For<IBus>();
        var dbContent = _container.Resolve<IFileManagerDbContext>();
        var apiContext = new FileServiceController(bus, dbContent);

        //Create a snapshot
        var releaseDate = DateTime.Now.Date;
        var result = await apiContext.ReleaseFile(new ReleaseFileModel
        {
            FileDate = releaseDate,
            FileType = "ProductFile"
        });

        Assert.That(result, Is.Not.Null, "Result is null");

        Assert.That(result, Is.TypeOf<OkResult>(), "Status code is not ok");

        bus.Received(1)
            .Send<IReleaseProductFiles>(Arg.Is<string>("FileManager.Service"), Arg.Is<Action<IReleaseProductFiles>>(
                action =>
                {
                    action.FileId = Guid.NewGuid();
                    action.RequestedDataDate = releaseDate;
                    action.RequestingUser = String.Empty;
                    action.RequestDateTime = DateTime.Now;
                }));
    }

这会导致错误 - 即使实际发送了消息。以下是错误消息:

NSubstitute.Exceptions.ReceivedCallsException : Expected to receive exactly 1 call matching:
    Send<IReleaseProductFiles>("Capelogic.Service", Action<IReleaseProductFiles>)
Actually received no matching calls.
Received 1 non-matching call (non-matching arguments indicated with '*' characters):
    Send<IReleaseProductFiles>("Capelogic.Service", *Action<IReleaseProductFiles>*)

我显然在这里遗漏了一些明显的东西。

1 个答案:

答案 0 :(得分:2)

问题在于Action<IReleaseProductFiles>的{​​{1}}参数 - 我们无法自动判断两个不同的动作是否相同。相反,NSubstitute依赖于相同的引用。因为测试代码和生产代码都创建了自己的Send实例,所以这些实例总是不同的,NSubstitute会说这些调用不匹配。

有一个few different options for testing this。这些示例与Action相关,但相同的想法适用于Expression<Func<>>

在这种情况下,我很想间接地测试它:

Action<>

我建议您查看前面提到的答案,看看是否更适合您的情况。