Search code examples
c#.net-corenunitxunitnunit-3.0

How to mock a method that is defined in multiple classes with same name


I have a factory method

public abstract class PFact 
{
   public abstract ResponseMessage P(Model request);
}

and I have different classes which overrides this method.

public class one : PFact 
{
    public override ResponseMessage P(Model request)
    {
        return response
    }
}

public class Two : PFact 
{
    public override ResponseMessage P(Model request)
    {
        return response
    }
}

and in another class I am calling these methods using

 var result = _F["One"].P(model);
 var result2 = _F["Two"].P(model);

I was trying to mock result and result 2 but a could not able to complete it. I am trying like

var mock = new Mock<PFact>()
mock.Setup(x => x.P(model)).Returns(response);

This is not mocking those classes one and two.

How can I explicitly mention both classes to mock separately for writing test case. I need to mock result and result2. please suggest me!


Solution

  • The Moq library (which I assume you are using) can only provide mock implementations of virtual methods on concrete classes.

    If you change your abstract method in PFact to be virtual:

    public virtual ResponseMessage P(Model request) {}

    Then you can create a mock for each class and provide different implementations.