c# - 如何使用 Neo4JClient 对方法进行单元测试
问题描述
我一直致力于使用 Neo4J 作为数据存储和 Neo4JClient ( https://github.com/Readify/Neo4jClient ) 来实现一个 .NET Core API 来构建应用程序的数据层。事情进展顺利,但我不知道如何使用客户端测试方法,以充分验证代码正在执行预期的操作。
使用 Neo4JClient 的示例方法:
private readonly IGraphClient _graphClient;
protected IGraphClient GraphClient => _graphClient;
public BaseRepository(GraphClient client)
{
_graphClient = client;
_graphClient.Connect();
}
public async Task<IList<TModel>> GetAllAsync()
{
var results = await GraphClient.Cypher.Match($"(e:{typeof(TModel).Name})")
.Return(e => e.As<TModel>())
.ResultsAsync;
return results.ToList();
}
是否有现有的用于模拟和单元测试方法的文档GraphClient
?我无法在 Google 搜索中找到有关该主题的任何内容。
解决方案
在有人想模拟它们之前,流畅的 API 似乎是个好主意。
但是,至少 Neo4JClient 图形客户端是基于接口的。
你可以做这样的事情(你需要将你的构造函数参数更改为IGraphClient
a 而不是GraphClient
.
public class BaseRepositoryTests
{
private readonly BaseRepository<Model> subject;
private readonly Mock<ICypherFluentQuery> mockCypher;
private readonly Mock<ICypherFluentQuery> mockMatch;
private readonly Mock<IGraphClient> mockGraphClient;
public BaseRepositoryTests()
{
mockMatch = new Mock<ICypherFluentQuery>();
mockCypher = new Mock<ICypherFluentQuery>();
mockCypher
.Setup(x => x.Match(It.IsAny<string[]>()))
.Returns(mockMatch.Object);
mockGraphClient = new Mock<IGraphClient>();
mockGraphClient
.Setup(x => x.Cypher)
.Returns(mockCypher.Object);
subject = new BaseRepository<Model>(mockGraphClient.Object);
}
[Fact]
public async Task CanGetAll()
{
IEnumerable<Model> mockReturnsResult = new List<Model> { new Model() };
var mockReturn = new Mock<ICypherFluentQuery<Model>>();
mockMatch
.Setup(x => x.Return(It.IsAny<Expression<Func<ICypherResultItem, Model>>>()))
.Returns(mockReturn.Object);
mockReturn
.Setup(x => x.ResultsAsync)
.Returns(Task.FromResult(mockReturnsResult));
var result = await subject.GetAllAsync();
Assert.Single(result);
}
public class Model { }
}
推荐阅读
- reactjs - REACT :将组件传递给将实现组件操作的函数
- xcode - 为osx设置地图以及用户当前位置
- java - 如何以多部分的形式发送响应
- system-verilog - 在系统verilog中循环对象的多维数组元素的标准方法是什么?
- python - 如何单击 Selenium 中的角度下拉菜单
- css - CSS 过渡仅在不活动时
- google-cloud-platform - Google Cloud Function - 依赖回购中代码的函数的默认更新行为是什么?
- javascript - Datepicker 在 IE 和 Chrome 中给出不同的结果
- c# - 在 datetimepicker 中禁用日历日期
- android - 如何计算arcore中的视野?