简体   繁体   English

最小起订量:如何将接口的模拟物转换回接口

[英]MOQ: How to cast a Mock of an Interface back to the interface

I am trying to write Unit Tests for a private method which expects an Interface (EnvDTE.Project). 我正在尝试为需要接口(EnvDTE.Project)的私有方法编写单元测试。

I'm using the Moq Framework to create a Mock of this Interface: 我正在使用Moq框架创建此接口的模拟:

Mock<Project> mock = new Mock<Project>();

After I'm setting the Properties, I want to cast this mock back to the Interface. 设置属性后,我想将此模拟转换回接口。 I'm trying this: 我正在尝试:

mock.As<Project>();                 //to implement the Project interface
Project project = mock as Project;  //this set Project to null
Project project = (Project)mock;    //this throws InvalidCastException

Is there another way to solve this Problem? 有没有其他方法可以解决此问题?

You can access your mocked object with: 您可以使用以下方法访问模拟对象:

var mock = new Mock<Project>(); 
Project project = mock.Object;

As mentioned, you do not need to mock out what you are doing. 如前所述,您无需模拟正在执行的操作。

Say we have a class called "Project". 假设我们有一个叫做“项目”的类。

public class Project
    {
        //Private method to test
        private bool VerifyAmount(double amount)
        {
            return (amount <= 1000);
        }
    }

We can then write a test using the PrivateObject approach you want to do. 然后,我们可以使用您要执行的PrivateObject方法编写测试。

[TestMethod]
public void VerifyAmountTest()
{
   //Using PrivateObject class
   PrivateObject privateHelperObject = new PrivateObject(typeof(Project));
   double amount = 500F;
   bool expected = true;
   bool actual;
   actual = (bool)privateHelperObject.Invoke("VerifyAmount", amount);

   Assert.AreEqual(expected, actual); 
 }

This will achieve what you want. 这将实现您想要的。

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

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