[英]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.
我的第一个问题是新建了其他类的一系列类,我通过使我想要测试的类的ctor(Search.cs)将它所需的类作为依赖项来修复它,它现在看起来像这样。
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? 我注入的类继承自另一个类,我有Resharper,我已经提取了接口,但问题是依赖类继承自另一个具体类 - 看我的意思?
public class SearchDatabaseConnect : DatabaseConnect, ISearchDatabaseConnect
{ // }
I don't know what to do about the inheritance on DatabaseConnect? 我不知道如何处理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.
显然,如果那不存在,我会全部设置我可以模拟一个ISearchDatabaseConnect然后我们去,但我坚持继承一个具体的类。 I am sure people have run into this before my googl'ing was a failure when it came to finding examples about this.
我相信人们已经遇到过这种情况,然而在我找到关于这方面的例子之前我的googl'ing失败了。
Thanks in advance for any useful suggestions. 提前感谢任何有用的建议。
Does DatabaseConnect
also have an interface extracted from it? DatabaseConnect
是否也有从中提取的接口? 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. 现在制作一个
Mock<ISearchDatabaseConnect>
将从两个接口获得所有“东西”。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.