首页 > 解决方案 > 如何使用 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 搜索中找到有关该主题的任何内容。

标签: c#unit-testingneo4j.net-coreneo4jclient

解决方案


在有人想模拟它们之前,流畅的 API 似乎是个好主意。

但是,至少 Neo4JClient 图形客户端是基于接口的。

你可以做这样的事情(你需要将你的构造函数参数更改为IGraphClienta 而不是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 { }
}

推荐阅读