我有一个无法修改的接口(interface),并且有大量的方法(基本上是重载——每个都略有不同)。
在某些情况下,接口(interface)上的每个方法都应该抛出相同的异常。有几个这样的场景,每个场景都有自己的异常(exception)(比如 SystemInMaintenanceModeException
、 ClientRateLimitedException
、 TheJanitorUnpluggedTheServerException
)。
有单元测试和这些异常抛出场景的设置量感觉非常愚蠢......像:
_mockedService.Setup(mock => mock.DoA(It.IsAny<string>()).Throws(expectedException);
_mockedService.Setup(mock => mock.DoB(It.IsAny<string>()).Throws(expectedException);
_mockedService.Setup(mock => mock.DoC(It.IsAny<string>()).Throws(expectedException);
...
_mockedService.Setup(mock => mock.DoX(It.IsAny<string>()).Throws(expectedException);
_mockedService.Setup(mock => mock.DoY(It.IsAny<string>()).Throws(expectedException);
_mockedService.Setup(mock => mock.DoZ(It.IsAny<string>()).Throws(expectedException);
Moq 是否可以配置为为模拟接口(interface)上的每个方法抛出指定的异常?PS:我知道严格行为会在任何调用时抛出异常,但我需要将其指定为异常。
最佳答案
Moq 使用 CaSTLe DynamicProxy,因此您可以像这样直接使用它
using System;
using System.Threading.Tasks;
using Castle.DynamicProxy;
public class Interceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
throw new NotImplementedException();
}
}
public interface ITest
{
void Test1();
Task Test2(string a);
int Add(int a1, int a2);
}
class Program
{
static void Main(string[] args)
{
{
ProxyGenerator generator = new ProxyGenerator();
var c = generator.CreateInterfaceProxyWithoutTarget<ITest>(new Interceptor());
try
{
var r = c.Add(11, 22);
Console.WriteLine(r);
}
catch (NotImplementedException e)
{
}
c.Test2("");
Console.ReadKey();
}
Console.WriteLine("Hello World!");
}
}
还要检查this question对于 Task 返回方法,您可能需要额外的逻辑,例如返回 Task.FromException。
关于c# - 可以将模拟配置为在任何方法调用上抛出指定的异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68687754/