c# - 模拟由您正在单元测试的函数调用的函数。使用起订量

标签 c# unit-testing moq

例如,您正在测试 getSomeString

public class Class1
{
    public Class1() {}

    public string getSomeString(string input)
    {
        //dosomething

        OtherClass class = new OtherClass();

        return class.getData();
    }
}

public class OtherClass
{
    public OtherClass() {/*some data*/}    

    public string getData()
    {
        //do something

        string aString = getAString(Input);

        //do something
    }

    public virtual string getAString(string input);
    {
        //do something to be mocked
        return somethingToBeMocked;
    }
}

因此您需要单元测试来模拟 getAString。你是怎么做到的?

我试过模拟 getAString 并希望测试使用模拟值,但这不起作用。

我已经尝试模拟 Class1 并将单元测试 class1 设置为模拟对象,但我不知道如何制作模拟的 getAString 传递到模拟的 class1 中。

我不知道该怎么办。

最佳答案

您不能只获取任何代码并对其进行单元测试。代码应该是可测试的。什么是可测试代码?这是一个依赖于抽象而不是实现的代码。避免依赖实现的唯一方法是通过依赖注入(inject)提供它们:

public class Class1()
{
    private IOtherClass _otherClass; // depend on this abstraction

    public Class1(IOtherClass otherClass) // constructor injection
    {
        _otherClass = otherClass;
    }

    public string getSomeString(string input)
    {
        //dosomething
        return _otherClass.getData(); // you don't know implementation
    }
}

其中IOtherClass接口(interface)由OtherClass实现

public interface IOtherClass
{
     string getData();
}

现在你的类依赖于抽象,你可以为测试模拟抽象:

string data = "Foo";
Mock<IOtherClass> otherClassMock = new Mock<IOtherClass>();
otherClassMock.Setup(oc => oc.getData()).Returns(data);
var class1 = new Class1(otherClassMock.Object);
// Act
string result = class1.getSomeString("Bar");
// Assert
Assert.That(result, Is.EqualTo(data));
otherClassMock.VerifyAll(); // check dependency was called

关于c# - 模拟由您正在单元测试的函数调用的函数。使用起订量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20402682/

相关文章:

c# 使用不支持的 html 敏捷包 URI 格式

c# - 单元测试 peek 完成时使用的异步回调方法

c# - 最小起订量单元测试 - 值不能为空

asp.net-mvc - 单元测试 Url.Action

c# - 如何从 mp4、wmv、flv、mov 视频中获取视频时长

c# - 如何删除 linq to Entity Framework 中的相关对象

c# - session 变量无法更新

python - 是否可以在 python 中过滤测试文件和具有不同模式的单独测试?

javascript - 如何使用 Jasmine 2.4.1(独立)设置基本的 Javascript 测试?

apache-flex - 是否有编写好的单元测试的优秀示例 Flex 项目?