我正在构建 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/