gpt4 book ai didi

c# - 如何使用 NSubstitute 模拟 protected 方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:00:48 25 4
gpt4 key购买 nike

public static void Mock(out IProgram prog, out IJson json)
{
prog = Substitute.For<IProgram>();
IJson = Substitute.For<IJson>();

prog.SaveProg(1, 1, 1, "Somthing", 1, DateTime.UtcNow,
(DateTime.UtcNow + TimeSpan.FromDays(10)),
10, "someemail@email.com", DateTime.UtcNow, 1)
.Returns(ObjectResult<int?>);
}

调用 Returns(ObjectResult<int?>) 时出现错误因为ObjectResult是保护类。我该如何解决这个问题,以便能够从实际方法中调用我模拟的方法?

最佳答案

NSubstitute 会在您调用该方法后覆盖替代方法的行为,但它实际上并不关心您是如何调用该方法的。这允许您通过反射调用它。

下面是一个非常详细的例子:

public class SomeRepository
{
public string ReadData() => ActuallyPerformDataReading();
protected virtual string ActuallyPerformDataReading() => "some wrong data";
}

public class SomeClass
{
SomeRepository _someRepository;
public SomeClass(SomeRepository someRepository)
{
_someRepository = someRepository;
}

public string ReadSomething() => _someRepository.ReadData();
}


var repositorySub = Substitute.For<SomeRepository>();
repositorySub.GetType().GetMethod("ActuallyPerformDataReading", BindingFlags.NonPublic | BindingFlags.Instance)
.Invoke(repositorySub, new object[] {}).Returns("some test data");
var sut = new SomeClass(repositorySub);

var result = sut.ReadSomething(); //"some test data"

关于c# - 如何使用 NSubstitute 模拟 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35468557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com