简体   繁体   中英

Unit testing test for Ok Result

I have the following (simplified) controller:

public async Task<IHttpActionResult> Profile(UpdateProfileModelAllowNulls modelNullable)
{         
    ServiceResult<ProfileModelDto> result = await _profileService.UpdateProfile(1);

    return Ok(result);         
}

And:

public async Task<ServiceResult<ProfileModelDto>> UpdateProfile(ApplicationUserDto user, UpdateProfileModel profile)
{
     //Do something...
}

and the following NUnit test:

[Test]
        public async Task Post_Profile()
        {
            var result = _controller.Profile(new UpdateProfileModelAllowNulls() { Email = "testEmail@tt.co.uk", DisplayName = "TestDisplay"}) as OkNegotiatedContentResult<Task<<ProfileModelDto>>;
            Assert.IsNotNull(result);            
        }

In my NUnit test, I am trying to check for an Ok result using this tutorial https://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api .

My problem is that I cannot convert to an OkNegotiatedContentResult , i assume because I am not passing in the correct object, but I cannot see what object I should be passing in. As far as I can see, I am passing in the correct object eg: OkNegotiatedContentResult<Task<<ProfileModelDto>>;

but this does not work.

I have also tried:

var result = _controller.Profile(new UpdateProfileModelAllowNulls() { Email = "testEmail@tt.co.uk", DisplayName = "TestDisplay"}) as OkNegotiatedContentResult<Task<IHttpActionResult>>;

But this does not work either.

Can anyone help?

您的控制器是Async,因此您应该将其称为:

var result = (_controller.Profile(new UpdateProfileModelAllowNulls() { Email = "testEmail@tt.co.uk", DisplayName = "TestDisplay"}).GetAwaiter().GetResult()) as OkNegotiatedContentResult<ProfileModelDto>;

As stated by @esiprogrammer, the method is async, so I needed to add the awaiter.

I was able to fix it by doing the following:

    var result = _controller.Profile(new UpdateProfileModelAllowNulls() { Email = "testEmail@wwasoc.co.uk", DisplayName = "TestDisplay"});
    var okResult = await result as OkNegotiatedContentResult<ServiceResult<ProfileModelDto>>;

I have accepted @esiprogrammer answer as he answered the question correctly, and also before me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM