Search code examples
c#testinginterfacemockingprivate

C#: test a method with an object parameter implementing a private interface


I have a first project with a method that returns a Model object instance implemented with a private class PrivateModel inheriting Model and a private interface IFoo.

Sample:

Project1:

public class Model {}
private interface IFoo {}
private class PrivateModel : Model, IFoo {}

// a sample class with the returning method
public class Bar
{
    public static Model CreateModelInstance()
    { return new PrivateModel(); }

    // code...
}

Project2:

// get model instance
var model = Bar.CreateModelInstance(); // return a Model

The second project calls a method "Act" with the model parameter, but Act's implementation tests if the model is a PrivateModel (with the IFoo implementation).

Project1:

public class Bar
{
    // code...

    public static bool Act(Model model)
    {
        // sample logic
        return model is IFoo;
    }
}

Now the question:

Because I have to test a method that performs calls to Act method (it's static), and I can't moke up it, I have to build an object that implements IFoo (that is private). Can I implement a class similar to TestClass: IFoo into the test project (a third project), or I have to use a Model returned from the Project1?


Solution

  • You can't implement private interface outside of assembly/class the interface is defined.

    Either redesign the code to be more testable or use model returned from Project1 (or whatever creates the model implementing correct interface)..

    Your case may actually be one of rare cases where private interface is useful - ensure very strict rules of object creation when you can't seal implementing classes for some reason. Whether it is useful for your case - your call.