从不同项目调用时返回 null 的模拟方法

编程入门 行业动态 更新时间:2024-10-28 04:30:01
本文介绍了从不同项目调用时返回 null 的模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个测试类:

using NSubstitute; using NUnit.Framework; using System; using System.Linq.Expressions; namespace MyTests { public class Tests { [Test] public void Test() { var companyBL = Substitute.For<ICompanyBL>(); companyBL.GetCompany(c => new { c.RegionID }).ReturnsForAnyArgs(new { RegionID = 4, }); var company = companyBL.GetCompany(c => new { c.RegionID }); var dataRetriever = new DataRetriever(companyBL); } } }

以及另一个项目中的这段代码:

and this code in another project:

namespace MyTests { using System; using System.Linq.Expressions; public interface ICompanyBL { T GetCompany<T>(Expression<Func<Company, T>> selector); } public partial class Company { public int RegionID { get; set; } } public class DataRetriever { public DataRetriever(ICompanyBL companyBL) { //This is null: var company = companyBL.GetCompany(c => new { c.RegionID }); } } }

company 变量是 null.但是,当代码都包含在同一个项目的同一个.cs文件中时,该值不是null.

The company var is null. However, when the code is all contained in the same .cs file in the same project, the value is not null.

为什么在另一个项目的另一个文件中使用值 null ?

Why is the value null when used in another file in another project?

NSubstitute 版本 = 1.10.0.0.

NSubstitute version = 1.10.0.0.

.NET Framework 版本 = 4.5.2.

.NET Framework version = 4.5.2.

在 Github 提交的问题:github/nsubstitute/NSubstitute/issues/598

Issue submitted in Github: github/nsubstitute/NSubstitute/issues/598

推荐答案

我不确定 nsubstitute 是如何工作的,但我相信您会遇到匿名类型仅在单个程序集中匹配的问题,它们在程序集中总是不同的.

I'm not sure how nsubstitute works but I believe you are running into issues where anonymous types only match inside single assembly, they are always different across assemblies.

大致上,您是在模拟 companyBL.GetCompany 并且您测试的代码调用 companyBL.GetCompany.

Roughly you are mocking companyBL.GetCompany<TestAssembly.AnonymousTypeForRegionID> and your tested code calls companyBL.GetCompany<ProductAssembly.AnonymousTypeForRegionID>.

最简单的修复 - 使用某种类型来传递这两个程序集之间共享的数据.甚至 Tuple 都可以.跨程序集边界返回/使用动态匿名类型中的更多想法

The easiest fix - use some type to pass data shared between those two assemblies. Even Tuple would do. More ideas in Return/consume dynamic anonymous type across assembly boundaries

更多推荐

从不同项目调用时返回 null 的模拟方法

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

发布评论

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

>www.elefans.com

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