0
我正在使用NUnit,應該和實體框架內存SQLite數據庫進行集成測試,並卡住了我的兩個測試用例不執行任何數據庫調用, (不等待執行)。c#測試異步任務 - 測試用例忽略等待 - NullReferenceException
控制器:
[HttpPost("DeleteOrganisations")]
public async Task<IActionResult> DeleteOrganisations([FromBody] DeleteOrganisationsModel model)
{
//Test case 2 fails here
if (model == null || !ModelState.IsValid)
{
return Ok(new GenericResultModel(_localizer["An_unexpected_error_has_occurred_Please_try_again"]));
}
List<OrganisationModel> organisations = (await _organisationService.GetOrganisations(model.OrganisationIds)).ToList();
//Test case 3 fails here
if (organisations == null || organisations.Count == 0)
{
return Ok(new GenericResultModel(_localizer["Could_not_find_organisations"]));
}
StatusModel status = await _statusService.GetStatus(StatusTypeEnum.StatusType.Organisation, StatusEnum.Status.Removed);
if (status == null)
{
return Ok(new GenericResultModel(_localizer["Could_not_find_status"]));
}
foreach (OrganisationModel organisation in organisations)
{
organisation.StatusId = status.Id;
}
List<OrganisationModel> updatedOrganisations = (await _organisationService.UpdateOrganisations(organisations)).ToList();
if (updatedOrganisations == null || updatedOrganisations.Count == 0)
{
return Ok(new GenericResultModel(_localizer["Could_not_remove_organisations"]));
}
if (updatedOrganisations.Count == 1)
{
return Ok(new GenericResultModel { Id = updatedOrganisations[0].Id });
}
return Ok(new GenericResultModel { Count = updatedOrganisations.Count });
}
測試:
[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);
}
}
測試用例1名經過因爲
StatusModel status = await _statusService.GetStatus(StatusTypeEnum.StatusType.Organisation, StatusEnum.Status.Removed);
被稱爲並且結果被期待已久的。
測試用例2和3失敗,因爲函數中沒有等待(if語句)。
消息:System.NullReferenceException:對象引用未設置爲 對象的實例。
我也許可以創建另一個測試爲不執行任何等待語句,並跳過了新的測試功能異步任務的結果,但我會得到的消息說:
因爲這呼叫未被等待,在呼叫完成之前繼續執行當前方法 。考慮將「await」 運算符應用於調用的結果。
該測試可能會通過,但我不喜歡兩個測試加上語法錯誤的想法。
你會怎麼做?
編輯
例外:
Message: System.NullReferenceException : Object reference not set to an instance of an object.
堆棧跟蹤:
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.
@Will我不包括任何異常細節,因爲我覺得它沒有任何有用的信息,但我已經編輯我的異常和堆棧跟蹤 – Reft
沒有有用的問題信息?哈哈哈。你的問題就在這裏:'Organisation.DeleteOrganisations'。您正在等待該方法中的某些內容,無論它是拋出異常。 **這與您的測試方法**完全無關。在DeleteOrganizations中放置一個斷點,調試測試並查看null。 – Will
讓我假裝我沒說:) :) – Reft