c# - 单元测试貂

标签 c# moq identityserver4 marten

我正在构建 IdentityServer4 的实现,使用 PostgreSQL 作为数据库,Marten 作为 ORM,GraphQL 作为 API。到目前为止,它在运行时运行得很好。但是,我也在尝试进行单元测试,但遇到了问题。我有 IdentityServer4 的 IClientStore 接口(interface)的自定义实现,其中 FindClientByIdAsync 方法的实现如下所示:

public async Task<Client> FindClientByIdAsync(string clientId)
{
    var client = await _documentSession.Query<dbe.Client>().FirstOrDefaultAsync(c => c.ClientId == clientId);
    return _mapper.Map<Client>(client); // AutoMapper conversion call
}

这在运行时效果很好。但是,我尝试进行以下测试来消除此代码:

[Fact]
public async Task FindClientByIdReturnsClient()
{
    var clients = new []
    {
        new dbe.Client
        {
            ClientId = "123"
        }
    }.AsQueryable();

    var queryable = new MartenQueryable<dbe.Client>(clients.Provider);
    // _documentSession is a Moq Mock
    _documentSession.Setup(x => x.Query<dbe.Client>()).Returns(queryable);

    var store = new ClientStore(_documentSession.Object, _mapper);

    var result = await store.FindClientByIdAsync("123");

    Assert.NotNull(result);
    Assert.Equal("123", result.ClientId);
}

当测试尝试执行 FindClientByIdAsync 方法时,出现错误:

System.InvalidCastException : Unable to cast object of type 'System.Linq.EnumerableQuery`1[StaticSphere.Persona.Data.Entities.Client]' to type 'Marten.Linq.IMartenQueryable'.

如果任何熟悉 Marten 的人都可以提供一些见解,那就太好了!我在 Google 上搜索了很久,但没有找到任何关于该主题的具体内容。

最佳答案

来自 Marten 创建者的引用,可能与此处相关 ( context ):

You can mock a bit of IDocumentSession (Load, Store, SaveChanges, maybe query by compiled query), but you’re gonna be in a world of hurt if you try to mock the Linq support.

因此,一种解决方案是进行集成测试,您可以从 official Marten's repository 中找到一些代码。或here .

关于c# - 单元测试貂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51814633/

相关文章:

c# - 使用IdentityServer4时如何在客户端检查access_denied?

c# - 在没有 for 或 foreach 的情况下使用 LINQ 进行反射

c# - 如何使用C#读取Excel文件的数据?

c# - 从具有特定模式的文本文件中读取文本

c# - 如何在没有循环的情况下将键数组和值数组连接到字典中?

c# - 如何测试 HttpWebRequest 依赖的方法?

mocking - 我应该在生产代码中使用模拟吗?

c# - 对继承类的最小起订量测试总是返回 null

authentication - 是否可以在不重定向到外部登录页面的情况下进行SPA身份验证

asp.net-core - ASP.NET Identity 和 IdentityServer 有什么区别?