使用匿名类型时,模拟方法返回 null

编程入门 行业动态 更新时间:2024-10-28 00:14:09
本文介绍了使用匿名类型时,模拟方法返回 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

本文发布于:2023-10-31 05:21:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545127.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   方法   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!