Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a class that inherits from another class

So here is the scenario, I am refactoring some spaghetti code. My first problem was a chain of classes that newed up other classes, I fixed this by making the ctor of the class I want to test (Search.cs) take the class it needs as a dependency, it looks like this now.

 public Search(XmlAccess xmlFile, SearchDatabaseConnect searchDatabaseConnection)
    {
        this.xmlFile = xmlFile;
        FsdcConnection = searchDatabaseConnection;
        Clear();
    }

I'm newing it up further up the chain. That is all good but I have a little problem.

The class that I am ctor injecting inherits from another class, I have Resharper and I have extracted interfaces but the problem is the dependency class inherits from another concrete class - see what I mean?

 public class SearchDatabaseConnect : DatabaseConnect, ISearchDatabaseConnect 
{ // }

I don't know what to do about the inheritance on DatabaseConnect? How do I mock that? Obviously if that wasn't there I would be all set I could mock an ISearchDatabaseConnect and away we go but I am stuck on the inheritance of a concrete class. I am sure people have run into this before my googl'ing was a failure when it came to finding examples about this.

Thanks in advance for any useful suggestions.

like image 541
Kenn Avatar asked Feb 07 '12 16:02

Kenn


1 Answers

Does DatabaseConnect also have an interface extracted from it? I think you should be able to set it up like:

public interface IDatabaseConnect

public class DatabaseConnect : IDatabaseConnect

public interface ISearchDatabaseConnect : IDatabaseConnect

public class SearchDatabaseConnect : DatabaseConnect, ISearchDatabaseConnect

And now making a Mock<ISearchDatabaseConnect> will get all the "stuff" from both interfaces.


Side-note, your method/constructor there should probably take in the interface, not the concrete:

public Search(XmlAccess xmlFile, ISearchDatabaseConnect searchDatabaseConnection) { ... }

That way you can inject the mock, like:

var mockedSearchDatabaseConnect = new Mock<ISearchDatabaseConnect>();
var search = new Search(xmlFile, mockedSearchDatabaseConnect.Object);
like image 170
CodingWithSpike Avatar answered Sep 29 '22 21:09

CodingWithSpike