c#测试异步任务 - 测试用例忽略await - NullReferenceException

时间:2017-07-07 19:04:53

标签: c# testing asynchronous nunit integration-testing

我使用NUnit,应该和实体框架内存中的SQLite数据库进行集成测试,并且卡在我的两个没有执行任何数据库调用的测试用例上(没有等待执行)。 / p>

控制器:

[TestFixture]
public class DeleteOrganisations : TestBase
{
    private OrganisationController _organisationController;

    [OneTimeSetUp]
    public void OneTimeSetUp()
    {
        //Controller
        _organisationController = new OrganisationController(null, Mapper, OrganisationService, StatusService, AuthenticationService);

        //Object Mother
        ObjectMother.InsertTestData();
    }

    public static IEnumerable TestCases
    {
        get
        {
            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = new List<int>() { 1 } }, 0, 1).SetName("DeleteOrganisations_Should_Delete_Data_When_OrganisationId_Exist");

            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = null }, 0, 0).SetName("DeleteOrganisations_Should_Not_Delete_Data_When_Null");
            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = new List<int>() { 2 } }, 0, 0).SetName("DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist");
        }
    }

    [Test, TestCaseSource(nameof(TestCases))]
    public async Task Test(DeleteOrganisationsModel model, int removedOrganisationCountBefore, int removedOrganisationCountAfter)
    {
        //Before
        int resultBefore = Database.Organisation.Include(o => o.Status).Count(o => o.Status.Name == StatusEnum.Status.Removed.ToString());

        resultBefore.ShouldBe(removedOrganisationCountBefore);

        //Delete
        await _organisationController.DeleteOrganisations(model);

        //After
        int resultAfter = Database.Organisation.Include(o => o.Status).Count(o => o.Status.Name == StatusEnum.Status.Removed.ToString());

        resultAfter.ShouldBe(removedOrganisationCountAfter);
    }
}

测试

StatusModel status = await _statusService.GetStatus(StatusTypeEnum.StatusType.Organisation, StatusEnum.Status.Removed);

测试用例1通过,因为

Message: System.NullReferenceException : Object reference not set to an instance of an object.

被调用,等待结果。

测试用例2和3失败,因为函数中没有等待(if语句)。

  

消息:System.NullReferenceException:未设置对象引用   一个对象的实例。

我可能会为没有执行任何await语句的结果创建另一个测试,并跳过新测试函数的异步任务,但后来我会收到消息:

  

因为没有等待此调用,所以执行当前方法   在通话结束前继续。考虑应用“等待”#39;   运算符到调用的结果。

测试可能会通过,但我不喜欢两个测试加上语法错误的想法。

你会做什么?

修改

例外:

Test Name:  DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist
Test FullName:  MyProject.Test.Api.Administration.Organisation.DeleteOrganisations.DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist
Test Source:    C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProject.Test\Api\Administration\Organisation\DeleteOrganisations.cs : line 42
Test Outcome:   Failed
Test Duration:  0:00:02.48

Result StackTrace:  at MyProject.Api.Controllers.Administration.OrganisationController.<DeleteOrganisations>d__8.MoveNext() in C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProject.Api\Controllers\Administration\OrganisationController.cs:line 114
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.Test.Api.Administration.Organisation.DeleteOrganisations.<Test>d__4.MoveNext() in C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProjectTest\Api\Administration\Organisation\DeleteOrganisations.cs:line 49
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object invocationResult)
   at NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext context)
Result Message: System.NullReferenceException : Object reference not set to an instance of an object.

堆栈跟踪:

{{1}}

1 个答案:

答案 0 :(得分:2)

Facepalm - 我忘了在testbase中注入localizer类。对不起,我的坏人。

这一行就在这里:

if (organisations == null || organisations.Count == 0)
{
    return Ok(new GenericResultModel(_localizer["Could_not_find_organisations"]));
}