小编Kyl*_* L.的帖子

如何使用 .NET Core 3 Web API 和 Moq 模拟 ExceptionContext 进行测试

为了在 .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轻松嘲笑?

c# unit-testing moq xunit .net-core

4
推荐指数
1
解决办法
4248
查看次数

使用 LINQ 和谓词时,Entity Framework Core 不生成Where 子句

错误地标记为重复 - 请参阅下面的答案

基本设置 - 我有一个应用程序上下文和一个用作 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)

c# sql linq entity-framework-core .net-core

1
推荐指数
1
解决办法
1251
查看次数

标签 统计

.net-core ×2

c# ×2

entity-framework-core ×1

linq ×1

moq ×1

sql ×1

unit-testing ×1

xunit ×1