我有这个测试类:
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 的模拟方法
发布评论