简体   繁体   English

测试继承的C#类

[英]Testing an inheriting C# class

I have the following code in c♯ but can not work out how to test it; 我在c♯中有以下代码,但无法确定如何测试它; I need to test aMethodUnderTest. 我需要测试aMethodUnderTest。 I can not change ABaseClass as it is in a library. 我无法更改ABaseClass,因为它在库中。 But if I am to test AClass I need to be able to set what theThing returns. 但是,如果我要测试AClass,我需要能够设置theThing返回的内容。 Does anyone have any ideas, or experience with this type of code testing? 有没有人有这种代码测试的想法或经验?

public ABaseClass
{
  protected ThingBaseClass theThing {get;}
  public virtual ....
  ...
}


public AClassUnderTest : ABaseClass
{
  public MyThing Thing
  {
    get
    {
      return (MyThing)base.theThing;
    }
  }

  public void aMethedUnderTest()
  {
    Thing.doSomething();
  }
}

Note: The initial value of theThing is null. 注意:theThing的初始值为null。 theThing has no public setter. theThing没有公共制定者。

我想你可以创建继承ABaseClass的mock,然后检查AClass.Thing是否返回与ABaseClassMock.theThing相同的结果

You can use mocking libraries like Moles. 您可以使用像Moles这样的模拟库。 Thus you can set the value of the "thing" from your test code. 因此,您可以从测试代码中设置“thing”的值。 http://research.microsoft.com/en-us/projects/moles/ http://research.microsoft.com/en-us/projects/moles/

You can create a mock of ABaseClass and still set theThing using MOQ (even though it has no setter) 你可以创建一个ABaseClass的模拟,并仍然使用MOQ设置theThing (即使它没有setter)

var mock = new Mock<ABaseClass>();
mock.SetupGet(x => x.theThing).Returns(\*Whatever you need*\);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM