使用匿名类型时,模拟方法返回 null [英] Mocked method returns null when using anonymous types

查看:49
本文介绍了使用匿名类型时,模拟方法返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

using NSubstitute;
using NUnit.Framework;
using System;
using System.Linq.Expressions;

namespace MyTests
{
    public interface ICompanyBL
    {
        T GetCompany<T>(Expression<Func<Company, T>> selector);
    }

    public partial class Company
    {
        public int RegionID { get; set; }
    }

    public class Tests
    {
        [Test]
        public void Test()
        {
            var companyBL = Substitute.For<ICompanyBL>();

            //Doesn't work
            companyBL.GetCompany(c => new { c.RegionID }).Returns(new
            {
                RegionID = 4,
            });

            //Results in null:
            var company = companyBL.GetCompany(c => new { c.RegionID });

            //This works:
            //companyBL.GetCompany(Arg.Any<Expression<Func<Company, Company>>>()).Returns(new Company
            //{
            //    RegionID = 4,
            //});

            //Results in non null:
            //var company = companyBL.GetCompany(c => new Company { RegionID = c.RegionID });
        }
    }
}

当我使用此代码时,company 变量为空.但是,注释掉的代码工作正常并导致非空值.

When I use this code, the company var is null. However, the commented out code works fine and results in a non null value.

为什么它不适用于匿名类型?有没有办法让它与匿名类型一起工作?

Why does it not work with the anonymous type? Is there some way to get this to work with anonymous types?

NSubstitute 版本 = 1.10.0.0.

NSubstitute version = 1.10.0.0.

.NET Framework 版本 = 4.5.2.

.NET Framework version = 4.5.2.

推荐答案

假设前面的选项可能不理想,如果您可以访问(在这种情况下)CompanyBL.

Assuming that the previous options may not be desirable, another approach may be available to you, if you have access to the (in this case) source for CompanyBL.

这种替代方法是将需要模拟的方法标记为 virtual 并使模拟从具体类 CompanyBL 继承,而不是实现整个接口.

This alternative is to mark the methods needed to be mocked as virtual and have the mock inherit from the concrete class CompanyBL rather than implement the whole interface.

您可能想要这样做的原因是为了使模拟不那么脆弱.. 即当有人扩展 ICompanyBL 接口时,他们将不需要向模拟添加实现.

The reason you may want to do this is to make the mock less fragile .. ie when someone extends the ICompanyBL interface they will not need to add implementations to the mock.

虽然这不是具体如何使用 NSubstitute 的答案,但我觉得这是一个值得的选择.一种变体可能是将 CompanyBL 更改为具有需要在模拟中替换的功能的受保护虚拟方法.编写更可测试的代码应该是一个值得关注的问题,可以说值得进行这些类型的更改.

While this is not an answer for specifically how to use NSubstitute I feel it is a worthwhile alternative. A variation may be to change CompanyBL to have protected virtual methods for functionality that needs to be replaced in the mock. Writing code that is more testable should be a concern which arguably merits these types of changes.

这篇关于使用匿名类型时,模拟方法返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆