加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 这可以用Moq嘲笑吗?

发布时间:2020-12-15 23:52:53 所属栏目:百科 来源:网络整理
导读:我正在努力模拟一些外部依赖项,并且遇到了一个第三方类的问题,它将构造函数作为另一个第三方类的实例.希望SO社区可以给我一些指导. 我想创建一个SomeRelatedLibraryClass的模拟实例,它接受它的构造函数SomeLibraryClass的模拟实例.如何以这种方式模拟SomeRel
我正在努力模拟一些外部依赖项,并且遇到了一个第三方类的问题,它将构造函数作为另一个第三方类的实例.希望SO社区可以给我一些指导.

我想创建一个SomeRelatedLibraryClass的模拟实例,它接受它的构造函数SomeLibraryClass的模拟实例.如何以这种方式模拟SomeRelatedLibraryClass?

回购代码……

这是我在测试控制台应用程序中使用的Main方法.

public static void Main()
{
    try
    {
        SomeLibraryClass slc = new SomeLibraryClass("direct to 3rd party");
        slc.WriteMessage("3rd party message");
        Console.WriteLine();

        MyClass mc = new MyClass("through myclass");
        mc.WriteMessage("myclass message");
        Console.WriteLine();

        Mock<MyClass> mockMc = new Mock<MyClass>("mock myclass");
        mockMc.Setup(i => i.WriteMessage(It.IsAny<string>()))
            .Callback((string message) => Console.WriteLine(string.Concat("Mock SomeLibraryClass WriteMessage: ",message)));

        mockMc.Object.WriteMessage("mock message");
        Console.WriteLine();
    }
    catch (Exception e)
    {
        string error = string.Format("---nThe following error occurred while executing the snippet:n{0}n---",e.ToString());
        Console.WriteLine(error);
    }
    finally
    {
        Console.Write("Press any key to continue...");
        Console.ReadKey();
    }
}

这是一个我用来包装一个第三方类并允许它成为Moq的类:

public class MyClass
{
    private SomeLibraryClass _SLC;

    public MyClass(string constructMsg)
    {
        _SLC = new SomeLibraryClass(constructMsg);
    }

    public virtual void WriteMessage(string message)
    {
        _SLC.WriteMessage(message);
    }
}

以下是我正在使用的第三方课程的两个示例(您无法编辑这些课程):

public class SomeLibraryClass
{
    public SomeLibraryClass(string constructMsg)
    {
        Console.WriteLine(string.Concat("SomeLibraryClass Constructor: ",constructMsg));
    }

    public void WriteMessage(string message)
    {
        Console.WriteLine(string.Concat("SomeLibraryClass WriteMessage: ",message));
    }
}

public class SomeRelatedLibraryClass
{
    public SomeRelatedLibraryClass(SomeLibraryClass slc)
    {
        //do nothing
    }

    public void WriteMessage(string message)
    {
        Console.WriteLine(string.Concat("SomeRelatedLibraryClass WriteMessage: ",message));
    }
}

解决方法

AFAIK,如果你想要模拟的类不是虚拟或接口 – 你不能用Moq模拟它.如果你的第三方图书馆没有实施他们的课程,我认为你运气不好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读