1

我正在整理 IdentityServer4 的实现,使用 PostgreSQL 作为数据库,Marten 作为 ORM,GraphQL 作为 API。到目前为止,它在运行时运行良好。但是,我也在尝试进行单元测试,并且遇到了问题。我有一个 IdentityServer4 的 IClientStore 接口的自定义实现,其中 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 的人都可以提供一些见解,那就太好了!我已经完成了我的谷歌时间,并没有找到任何关于这个主题的具体内容。

4

1 回答 1

2

来自 Marten 的创建者的引述可能与此处相关(上下文):

您可以模拟一些 IDocumentSession(加载、存储、SaveChanges,也许通过编译查询进行查询),但是如果您尝试模拟 Linq 支持,您将会受到伤害。

因此,一种解决方案是进行集成测试,您可以从Marten 的官方存储库此处找到一些代码。

于 2018-08-13T08:51:20.637 回答