美好的一天,
我有一个执行注册表查找的类来确定应用程序的安装位置(在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:Expression不是方法调用: x => x.Path == .workstationInstallationPath
所以我的问题是:我想测试x.Path == wrokstationInstallationPath。
我如何在.Verify()方法中执行此操作?
或者我最好使用Assert?
TIA,
COSON
答案 0 :(得分:2)
你真的不需要在这里使用模拟。
您的 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);
}
答案 1 :(得分:2)
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,那么您实际上只是断言这两个值都是相同的,而不是验证是否通过某种方法调用来设置它们。