如何使用Neo4JClient进行单元测试方法

时间:2019-02-28 23:25:34

标签: c# unit-testing neo4j .net-core 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搜索中找到关于该主题的任何内容。

1 个答案:

答案 0 :(得分:1)

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

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

您可以执行以下操作(您需要将构造函数参数更改为IGraphClient而不是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 { }
}