草庐IT

关于 c#:Moq 上的扩展方法返回 null

codeneng 2023-03-28 原文

Extension Method on Moq returns null

我尝试测试一些调用扩展方法的函数的结果。这个扩展方法是在一个接口上定义的。测试设置创建了所述接口的模拟。对于这个模拟,配置了两个设置。在模拟接口实现上调用这些设置函数时,一切都按预期工作。 (请参阅 TestMockSetupSourceClassA 和 TestMockSetupSourceClassB)但是当在扩展方法中进行这些调用时,结果为空。 (参见 TestDoClassStuff)

我已经建立了一个测试项目:https://github.com/sschauss/MoqExtensionMethodTest

扩展

1
2
3
4
5
6
7
8
9
public static class ExtensionClass
{
    public static TResult DoExtensionStuff<TResult>(this ISomeInterface someInterface, object initialObject,
        params object[] objects)
    {
        var result = someInterface.DoInterfaceStuff<TResult>(initialObject);
        return objects.Aggregate(result, (agg, cur) => someInterface.DoInterfaceStuff(cur, agg));
    }
}

实施

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SomeClass
{
    private readonly ISomeInterface _someInterface;

    public SomeClass(ISomeInterface someInterface)
    {
        _someInterface = someInterface;
    }

    public TargetClass DoClassStuff(SourceClassA sourceClassA, SourceClassB sourceClassB)
    {
        return _someInterface.DoExtensionStuff<TargetClass>(sourceClassA, sourceClassB);
    }
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class UnitTest
{
    private readonly SomeClass _sut;
    private readonly SourceClassA _sourceA;
    private readonly SourceClassB _sourceB;
    private readonly TargetClass _target;
    private readonly Mock<ISomeInterface> _someInterfaceMock;

    public UnitTest()
    {
        _sourceA = new SourceClassA
        {
            Integer = 1
        };
        _sourceB = new SourceClassB
        {
            String ="stringB"
        };
        _target = new TargetClass
        {
            Integer = 2,
            String ="stringT"
        };
        _someInterfaceMock = new Mock<ISomeInterface>();
        _someInterfaceMock.Setup(m => m.DoInterfaceStuff<TargetClass>(_sourceA)).Returns(_target);
        _someInterfaceMock.Setup(m => m.DoInterfaceStuff(_sourceB, _target)).Returns(_target);
        _sut = new SomeClass(_someInterfaceMock.Object);
    }

    [Fact]
    public void TestDoClassStuff()
    {
        var result = _sut.DoClassStuff(_sourceA, _sourceB);

        result.Should().BeEquivalentTo(_target);
    }

    [Fact]
    public void TestMockSetupSourceClassA()
    {
        var result = _someInterfaceMock.Object.DoInterfaceStuff<TargetClass>(_sourceA);

        result.Should().BeEquivalentTo(_target);
    }

    [Fact]
    public void TestMockSetupSourceClassB()
    {
        var result = _someInterfaceMock.Object.DoInterfaceStuff(_sourceB, _target);

        result.Should().BeEquivalentTo(_target);
    }
}

问题与 Aggregate 扩展名、它的通用参数参数以及您对 Setup 的模拟有关。

扩展方法DoExtensionStuffparams是一个object数组所以当调用`

1
T2 DoInterfaceStuff<T1, T2>(T1 parameter1, T2 parameter2)

Aggregate 委托中,您实际上是在传递

1
 (TResult agg, object cur) => someInterface.DoInterfaceStuff<object,TResult>(cur, agg)

模拟未配置为处理的。

在更改 _someInterfaceMock.Setup 之后,在这种特殊情况下,显式更改为

1
2
3
 _someInterfaceMock
    .Setup(m => m.DoInterfaceStuff<object, TargetClass>(_sourceB, _target))
    .Returns(_target);

此场景中的所有测试都能够成功完成。

Moq 的问题是,当一个 mock 没有被明确告知期望什么时,默认情况下它会为引用类型返回 null。

有关关于 c#:Moq 上的扩展方法返回 null的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  9. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐