Moq验证表达式

本文关键字:表达式 验证 Moq | 更新日期: 2023-09-27 18:21:47

好日子,

我有一个类,它执行注册表查找以确定应用程序的安装位置(在64位计算机上)。

我正在写一个单元测试来验证这一点,下面是我所拥有的:

[Test, Explicit]
public void Validate64Bit()
{
    wsMock.Setup(x => x.IsInstalled).Returns(true);
    wsMock.Setup(x => x.Path).Returns(@"C:'Program Files (x86)'DIRP'");
    IWorkstationLocator workstationLocator = new WorkstationLocator();
    string workstationInstallationPath = workstationLocator.Path;
    Assert.That(workstationInstallationPath != string.Empty, "The install path should exist.");
    wsMock.Verify(x => x.Path == workstationInstallationPath, 
        "64-bit Workstation Install Path should match:  " + @"C:'Program Files (x86)'DIRP'");
    }

但我得到了一个错误:

System.ArgumentException:表达式不是方法调用:x=>x.路径===.workstationInstallationPath

所以我的问题是:我想测试x.Path==wrokstationInstallationPath。

如何在.Verify()方法中执行此操作?

还是我最好使用断言?

TIA,

coson

Moq验证表达式

您实际上不需要在这里使用mock。

您的sut似乎是WorkstationLocator类,您所检查的只是Path属性是否等于特定值。

你可以简单地做:

[Test, Explicit]
public void Validate64Bit()
{
    var expectedPath = @"C:'Program Files (x86)'DIRP'";
    IWorkstationLocator workstationLocator = new WorkstationLocator();
    Assert.AreEqual(expectedPath, workstationLocator.Path, 
        "64-bit Workstation Install Path should match:  " + expectedPath);
}

Moq的Verify通常用于验证是否调用了特定方法。例如,

// Verify with custom error message for failure
mock.Verify(foo => foo.Execute("ping"), "When doing operation X, the service should be pinged always");

如果你在测试x.Path==workstationInstallationPath,你实际上只是断言两个值是相同的,而不是验证其中一个是由某种方法调用设置的。