Desiigner
Desiigner

Reputation: 69

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?

Upvotes: 2

Views: 4476

Answers (2)

Wheels73
Wheels73

Reputation: 2890

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.

Upvotes: 0

Mueui
Mueui

Reputation: 181

You can access your mocked object with:

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

Upvotes: 5

Related Questions