NUnit-用于测试事务的单元测试用例

Cha*_*tra 5 c# nunit unit-testing

我有如下方法。

我想为以下方法编写两个测试用例。

1) A successful transaction with committing data

2) A failed transaction with rollback data

How can I write a test case with transaction involved and make success and fail?

public async Task<List<string>> UpdateRequest(MetaData data, List<string> Ids, string requestedBy)
{
    var transaction = await _databaseUtility.CreateTransaction(ConnectionString);

    var messages = new List<string>();

    try
    {
        // Update data
        await _testDal.Update(data, requestedBy, transaction);

        // Update status
        await _sampleDal.UpdateStatus(Ids, requestedBy, transaction);

        // Update saved data
        await _testDal.UpdateSavedData(data, requestedBy, transaction);

        _databaseUtility.CommitTransaction(transaction);
    }
    catch (Exception exception)
    {
        _databaseUtility.RollbackTransaction(transaction);
    }

    return messages;
}
Run Code Online (Sandbox Code Playgroud)

Pav*_*ski 4

您可以通过使用 NUnit 内置TestCaseSource属性和TestCaseData类来实现它。

[TestCaseSource(nameof(TestCases))]
public List<string> TestTransaction(MetaData data, List<string> ids, string requestedBy)
{
    return testObject.UpdateRequest(data, ids, requestedBy).GetAwaiter().GetResult();
}

public static IEnumerable TestCases
{
    get
    {
        //successful
        yield return new TestCaseData(new MetaData(), new List<string> { "1", "2" }, "test").Returns(new List<string> { "test1", "test2" });
        //failed
        yield return new TestCaseData(null, new List<string> { "1", "2" }, "test").Returns(new List<string> { "test1", "test2" });
        //another failed
        yield return new TestCaseData(new MetaData(), new List<string> { "1", "2" }, string.Empty).Returns(new List<string> { "test1", "test2" });
    }
}
Run Code Online (Sandbox Code Playgroud)

这里有几点

  • 为什么方法List中需要消息UpdateRequest?它只是初始化,没有添加值。在上面的代码片段中,从方法返回的消息列表UpdateRequest与预期结果简单匹配,但您Assert也可以在此处编写任何内容
  • 失败的交易取决于您的逻辑,您可以传递导致异常的无效数据,在代码片段中我使用了空 MetadatarequestedBy
  • async Task<List<string>>返回结果同步执行,以匹配预期返回结果List<string>。异步测试用例源是NUnit github中的开放提案

作为一种选择,您还可以为成功和失败的事务编写单独的测试并UpdateRequest异步调用方法。

到目前为止,您还没有共享组件的详细信息,并且很难对 DAL 做出假设,但是如果您想对Update方法使用模拟,您可以尝试使用Moq库和Task.FromResult方法来响应/返回值,因为它这个答案中描述的