为了在 .NET Core 3 中正确测试自定义 ExceptionFilterAttribute,我们需要使用 Moq 在 Xunit 测试中模拟 ExceptionContext。我怎样才能做到这一点?
异常过滤器:
public class CustomExceptionFilter : ExceptionFilterAttribute
{
public override OnException(ExceptionContext context)
{
/* Code here that handles exceptions */
}
}
Run Code Online (Sandbox Code Playgroud)
我到处都找过了,但找不到一种好方法来模拟这些东西,以确保不会因其他缺失的依赖项而引发异常。我怎样才能ExceptionContext轻松嘲笑?
错误地标记为重复 - 请参阅下面的答案
基本设置 - 我有一个应用程序上下文和一个用作 DAO 的抽象:
某个实体:
public class SomeEntity
{
public string MyProp { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
数据库上下文:
public class ApplicationContext : DbContext
{
public DbSet<SomeEntity> SomeEntities { get; set; }
/* Rest of the DbContext doesn't matter. */
}
Run Code Online (Sandbox Code Playgroud)
道:
public class DAO
{
private readonly DbSet<SomeEntity> _dbSet;
public DAO(ApplicationContext context)
{
_dbSet = context.SomeEntities;
}
public IEnumerable<SomeEntity> Where(Func<SomeEntity, bool> predicate)
{
return _dbSet.Where(predicate);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
Dao dao = new Dao(/* whatever for instantiation …Run Code Online (Sandbox Code Playgroud)