[英]How to test a virtual method defined in an abstract class?
I need to unit-test a virtual method defined in an abstract class. 我需要对抽象类中定义的虚拟方法进行单元测试。 But the base class is abstract, so I can't create an instance of it.
但是基类是抽象的,因此我无法创建它的实例。 What do you recommend me to do?
你推荐我做什么?
This is a follow up to the following question: I am thinking about if it is possible to test via an instance of a subclass of the abstract class. 这是对以下问题的回应: 我正在考虑是否可以通过抽象类的子类的实例进行测试。 Is it a good way?
这是个好方法吗? How can I do it?
我该怎么做?
I'm not sure what your abstract class looks like, but if you have something like: 我不确定您的抽象类是什么样子,但是如果您有类似的东西:
public abstract class SomeClass
{
public abstract bool SomeMethod();
public abstract int SomeOtherMethod();
public virtual int MethodYouWantToTest()
{
// Method body
}
}
And then, as @David suggested in the comments: 然后,正如@David在评论中建议的那样:
public class Test : SomeClass
{
// You don't care about this method - this is just there to make it compile
public override bool SomeMethod()
{
throw new NotImplementedException();
}
// You don't care about this method either
public override int SomeOtherMethod()
{
throw new NotImplementedException();
}
// Do nothing to MethodYouWantToTest
}
Then you just instantiate Test
for your unit test: 然后,您只需为单元测试实例化
Test
:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
SomeClass test = new Test();
// Insert whatever value you expect here
Assert.AreEqual(10, test.MethodYouWantToTest());
}
}
There's no rule that says a unit test can't define its own classes. 没有规则说单元测试不能定义自己的类。 This is a fairly common practice (at least for me anyway).
这是相当普遍的做法(至少对我而言)。
Consider the structure of a standard unit test: 考虑标准单元测试的结构:
public void TestMethod()
{
// arrange
// act
// assert
}
That "arrange" step can include any reasonable actions (without side-effects outside of the test) which set up what you're trying to test. 该“安排”步骤可以包括设置您要测试的内容的任何合理的操作(没有测试外部的副作用)。 This can just as easily include creating an instance of a class whose sole purpose is to run the test.
这可以很容易地包括创建一个类的实例,该类的唯一目的是运行测试。 For example, something like this:
例如,如下所示:
private class TestSubClass : YourAbstractBase { }
public void TestMethod()
{
// arrange
var testObj = new TestSubClass();
// act
var result = testObj.YourVirtualMethod();
// assert
Assert.AreEqual(123, result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.