简体   繁体   中英

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).

I'm using the Moq Framework to create a Mock of this Interface:

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.

[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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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