Bhuvan Gopal
Bhuvan Gopal

Reputation: 43

How to create mock for method that is called using object instance in MOQ C#?

I created Test for a method that is being tested using MOQ & NUnit. The method to be tested will will another method using an object of that corresponding class. When I try to mock that called method, I am not able to invoke the mocked method. How to mock this method, because my testing method is using the other said method. Please help me on this.

public DataSet ExecuteCondition()
{
  var ObjClass1 = new Class1();
  ....
  var result = ObjClass1.VerifyPrecondition(query);
  ....
}


public class Class1:IClass1
{
 public string VerifyPrecondition(string query)
 {
   ....
   return text;
 }
}

Upvotes: 0

Views: 1027

Answers (1)

Wojciech Rak
Wojciech Rak

Reputation: 600

So, I suppose this should look like this:

Class with ExecuteCondition() method:

public class DataClass
{
    private readonly IClass1 _class1;

    public DataClass(IClass1 class1)
    {
        _class1 = class1;   
    }

    public DataSet ExecuteCondition()
    {
            //....
        var result = _class1.VerifyPrecondition(query);
            //....
    }
}

Test:

[Test]
public void Test()
{
    var mockClass1 = new Mock<IClass1>();
    mockClass1.Setup(x => x.VerifyPrecondition(It.IsAny<string>())).Returns("test");
    var dataClass = new DataClass(mockClass1.Object);

    dataClass.ExecuteCondition();

    //Assert
}

Upvotes: 1

Related Questions