c# - 可以将模拟配置为在任何方法调用上抛出指定的异常吗?

标签 c# unit-testing moq

我有一个无法修改的接口(interface),并且有大量的方法(基本上是重载——每个都略有不同)。
在某些情况下,接口(interface)上的每个方法都应该抛出相同的异常。有几个这样的场景,每个场景都有自己的异常(exception)(比如 SystemInMaintenanceModeExceptionClientRateLimitedExceptionTheJanitorUnpluggedTheServerException )。
有单元测试和这些异常抛出场景的设置量感觉非常愚蠢......像:

_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/

相关文章:

asp.net - 模拟的 UserManager 和 roleManager 方法返回 null

c# - 使用 Moq 部分模拟类内部方法

c# - ServiceStack.OrmLite : Reading back a TimeSpan using Untyped API results in InvalidCastException

c# - 引用实例化另一个的对象?

python - 为什么 Python 中的单元测试需要 -m 选项?

unit-testing - Yii2 + Codeception : How to use fixtures?

c# - System.NotSupportedException : Unsupported expression: x => x

c# - http请求不包含.net core 2.1中createresponse的定义

c# - 扩展 TFS 以在工作项中包含自定义字段

java - 如何测试线程之间值的可见性