简体   繁体   English

如何对依赖于本地声明的对象行为的ac#方法进行单元测试?

[英]How to unit test a c# method that has dependency on a locally declared object's behavior?

I have ac# method that is dependent on the return value of a service call that it makes with an object that is locally instantiated. 我有一个ac#方法,该方法取决于它使用本地实例化的对象进行的服务调用的返回值。 How can I test it without making change to the code. 我如何在不更改代码的情况下进行测试。 I am aware that dependency injection would have made it testable or passing dependency to out of this method would make it testable, but that is not the case here. 我知道依赖注入将使其可测试,或者将依赖传递给该方法之外的方法将使其可测试,但是这里不是这种情况。

My method looks something like this: 我的方法看起来像这样:

public class Animal
{ 
    int Weight;
    public int CalculateActualWeight()
    {
       var weightFactory = new WeightFactory();
       var weight = Weight + weightFactory.GetEatenAmount();
       return weight;
    }
}

The method to be tested is CalculateActualWeight(). 要测试的方法是CalculateActualWeight()。

You can fake the returned result of a function using something like Moq. 您可以使用Moq之类的方法来伪造函数的返回结果。 You can set it up (it your test) so that your dependency returns whatever you tell it to return. 您可以对其进行设置(测试),以便您的依赖项返回您告诉它返回的内容。 Then you can test the dependent method knowing what the result of the other method will be. 然后,您可以测试依赖方法,从而知道另一种方法的结果。

var mock = new Mock<IYourClass>();
mock.Setup(m => m.Method()).Returns(true);

That will make your Method() always return true so that you can test the other. 这将使您的Method()始终返回true,以便您可以测试另一个。 More info on Moq here. 有关Moq的更多信息,请点击此处。

If you cannot change the production code, the only way to test it would be to write a test that surrounds how the locally instantiated object functions as well. 如果您无法更改生产代码,则唯一的测试方法是编写一个围绕本地实例化对象功能的测试。

You could also use self stubbing , but that isn't a recommended practice, and will only work if the object under test has functions that can be mocked to replace what you need. 您也可以使用self stubbing ,但这不是推荐的做法,并且仅在被测对象具有可被模拟以替换您需要的功能的情况下才有效。

example: 例:

[Test]
public void Test()
{
    //do stuff so that a "real" new WeightFactory() will return what you want
    //(this will require you to go figure out how the WeightFactory works), 
    //4 is just an example of your desired result
    SetUpSystemSoThatWeightFactoryProduces(4);

    var testAnimal = new Animal();
    testAnimal.Weight = 14;

    Assert.That(testAnimal.CalculateWeight(), Is.EqualTo(18));
}

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

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