简体   繁体   English

Moq验证表达式

[英]Moq Verify Expression

Good Day, 美好的一天,

I have a class that performs a registry lookup to determine where an application is installed (on a 64-bit machine). 我有一个执行注册表查找以确定在哪里安装应用程序(在64位计算机上)的类。

I'm writing a unit test in an attempt to verify that and here's what I have: 我正在编写一个单元测试,试图验证这一点,这就是我所拥有的:

[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\");
    }

But I'm getting an error: 但是我遇到一个错误:

System.ArgumentException : Expression is not a method invocation: x => x.Path == .workstationInstallationPath System.ArgumentException:表达式不是方法调用:x => x.Path == .workstationInstallationPath

So my question is: I want to test if x.Path == wrokstationInstallationPath. 所以我的问题是:我想测试x.Path == wrokstationInstallationPath。

How would I do this in a .Verify() method? 我将如何在.Verify()方法中执行此操作?

Or am I better off using an Assert? 还是我最好使用断言?

TIA, TIA,

coson

You don't really need to use a mock here. 您实际上不需要在这里使用模拟。

Your sut appears to be the WorkstationLocator class and all you check is that the Path property is equal to a particular value. 您的输入似乎是WorkstationLocator类,您所要做的只是检查Path属性是否等于特定值。

You could simply do: 您可以简单地执行以下操作:

[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's Verify is typically used to verify that a particular method was called . Moq的Verify通常用于验证是否调用了特定方法。 For example, 例如,

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

If you're testing that x.Path == workstationInstallationPath, you're really just asserting that both values are the same, not verifying that either was set by some sort of method invocation. 如果要测试x.Path == WorkstationInstallationPath,则实际上只是在断言这两个值相同,而没有验证这两个值是由某种方法调用设置的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM