我有一个工厂类返回如下委托(delegate)(GetDelegate 方法)
public interface IFactory
{
Func<int, string> GetDelegate(bool isValid);
}
public class AFactory : IFactory
{
private readonly IService1 _service1;
private readonly IService2 _service2;
public AFactory(IService1 service1, IService2 service2)
{
_service1 = service1;
_service2= service2;
}
public Func<int, string> GetDelegate(bool isValid)
{
if (isValid)
return _service1.A;
return _service2.B;
}
}
public interface IService1
{
string A(int id);
}
public interface IService2
{
string B(int id);
}
我一直在尝试为 GetDelegate 编写单元测试,但不知道如何根据 isValid 断言返回了特定的 Func
我的单元测试尝试如下(我对此并不满意)
[Test]
public void ShouldReturnCorrectMethod()
{
private var _sut = new AFactory(new Mock<IService1>(), new Mock<IService2>());
var delegateObj = _sut.GetDelegate(true);
Assert.AreEqual(typeof(string), delegateObj.Method.ReturnType);
Assert.AreEqual(1, delegateObj.Method.GetParameters().Count());
}
非常感谢任何帮助
谢谢
最佳答案
一种方法是模拟调用 IService1.A
和 IService2.B
的结果,就像您直接调用它们一样。然后,您可以检查当您调用返回的委托(delegate)时,您是否得到了预期的答案(并且调用是对适当的服务进行的)。
关于c# - 如何使用 Moq 和 NUnit 测试委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31189565/