DEV Community

Discussion on: Feb. 21, 2020: What did you learn this week?

Collapse
 
ffirsching profile image
Felix Firsching

This week I learned more about the Net Core Request Pipeline.
Especially, that when using a controller with non default ActionResult return type, like for example BadRequest(), that these ActionResults will get wrapped in another ActionResult, which makes unit testing kind of tedious. E.g.:


        // controller method
        [Route("{id:int}")]
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<ActionResult<Author>> GetOneById(int id)
        {
            Author result = await _authorService.GetById(id);

            if (result != null)
            {
                return result;
            }
            else
            {
                return NotFound();
            }
        }

        // tests
        [Fact(DisplayName = "Should return correct author by id")]
        public async Task Should_Return_Author_By_Id()
        {
            // arrange
            var expected = fixture.authorList.Where(author => author.Id == 1).FirstOrDefault();

            // act
            var result = await controller.GetOneById(1);

            // assert
            Assert.IsType<ActionResult<Author>>(result);
            Assert.Equal(expected, result.Value); // Using Value since ReturnType is ActionResult<Author>, so we need to access the value
        }

        [Fact(DisplayName = "Should return NotFound()")]
        public async Task Should_Return_Author_NotFound()
        {
            // act
            var result = await controller.GetOneById(999);

            // assert
            Assert.Null(result.Value);
            Assert.IsType<ActionResult<Author>>(result); // check method return type matches
            Assert.IsType<NotFoundResult>(result.Result); // check actual return is as expected
        }
Collapse
 
nickytonline profile image
Nick Taylor

Mario approves. He's just not sure which pipeline to jump into 😉

Someone playing Super Mario 1