Moq验证对象参数

rhu*_*hes 72 .net c# unit-testing moq

我正在尝试验证一个类的参数.正在测试的代码很好.该错误正在测试中.

我尝试过两种方法,都失败了.

以下是我的尝试:

1:

this.MockImageResizeFilter.Verify(m => m.Filter(this.UploadedFileData, new ImageFilterOptions()
    {
        Width = 256,
        Height = 256,
    }));
Run Code Online (Sandbox Code Playgroud)

即使作为第二个参数传递的对象具有相同的属性,这也总是失败.第一个参数验证正常.

2:

this.MockImageResizeFilter.Setup(m => m.Filter(It.IsAny<byte[]>(), It.IsAny<ImageFilterOptions>()))
    .Callback<byte[], ImageFilterOptions>((data, options) =>
        {
            Assert.AreEqual(this.UploadedFileData, data, "data");
            Assert.AreEqual(filterOptions.Width, options.Width, "Width");
            Assert.AreEqual(filterOptions.Height, options.Height, "Height");
        }
    );
Run Code Online (Sandbox Code Playgroud)

这总是通过,即使它应该失败.回调中的Asserts确实失败了,但是异常没有传递给外部上下文,因此测试总是通过.

你能帮我找到我做错的事吗?

Cri*_*scu 115

第一次尝试更接近您想要实现的目标.

它失败的原因是Moq(可能)Object.Equals在封面下使用来测试ImageFilterOptions调用方法的参数是否与您在调用中提供的 参数相同Verify.

它们不可能是同一个实例,因为在Verify你创建一个new ImageFilterOptions().

您可以使用Moq的It.Is语法来提供验证参数是否为预期参数的表达式,而不是以这种方式执行参数检查.

在您的情况下,您要检查参数是否为类型ImageFilterOptions,Width并且Height要设置为和256.允许您这样做的表达式是:

It.Is<ImageFilterOptions>(p => p.Width == 256 && p.Height == 256)
Run Code Online (Sandbox Code Playgroud)

所以,你的电话Verify可能如下:

this.MockImageResizeFilter.Verify(m => m.Filter(
            this.UploadedFileData,
            It.Is<ImageFilterOptions>(p => p.Width == 256 && p.Height == 256)));
Run Code Online (Sandbox Code Playgroud)


Mar*_*ese 15

Moq 的Verify方法仅告诉您该方法从未使用您指定的参数调用,而没有解释哪个参数(或参数的哪个属性)是错误的。要获得详细信息,请使用回调将参数保存到变量,然后对其进行断言:

ImageFilterOptions passedOptions = null;
this.MockImageResizeFilter.Setup(m => m.Filter(It.IsAny<byte[]>(), It.IsAny<ImageFilterOptions>()))
    .Callback<byte[], ImageFilterOptions>((data, options) =>
    {
        passedOptions = options
    });

// <exercise the mocked object>

this.MockImageResizeFilter.Verify(m => m.Filter(this.UploadedFileData, It.IsAny<ImageFilterOptions>());
Assert.AreEqual(expectedOptions.Width, passedOptions.Width, "Width");
Assert.AreEqual(expectedOptions.Height, passedOptions.Height, "Height");

// (If you wanted, you could also use the callback technique to check that
// `this.UploadedFileData` was passed in for the first parameter.)
Run Code Online (Sandbox Code Playgroud)

这准确地告诉您哪个参数/属性是错误的。

您还可以跳过单独测试每个属性,这在处理具有许多属性的对象时非常有用:

using FluentAssertions;

// ...

passedOptions.Should().BeEquivalentTo(expectedOptions);
Run Code Online (Sandbox Code Playgroud)

(请注意,BeEquivalentTo确实指出了个别属性的失败。)