Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
//AuthController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BookApi.Data.Repository;
using BookApi.DataModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BookApi.Controllers
{
[Produces("application/json")]
[Route("api/Author")]
public class AuthorController : Controller
{
private readonly IAuthorRepository _authorRepository;
public AuthorController(IAuthorRepository authorRepository)
{
_authorRepository = authorRepository;
}
[HttpPost]
public IActionResult CreateAuthor([FromBody] Author author)
{
if(author == null)
{
return BadRequest();
}
if(ModelState.IsValid)
{
_authorRepository.Add(author);
return CreatedAtRoute("GetAuthor", new { id = author.Id }, author);
}
return BadRequest();
}
[HttpGet("{id}", Name = "GetAuthor")]
public IActionResult GetById(int id)
{
var item = _authorRepository.Get(id);
if(item == null)
{
return NotFound();
}
return new OkObjectResult(item);
}
}
}
//AuthControllerTest.cs
using BookApi.Controllers;
using BookApi.Data.Repository;
using BookApi.DataModels;
using Microsoft.AspNetCore.Mvc;
using Moq;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace BookApiTest.UnitTests.Controller
{
public class AuthorControllerTest
{
private Author GetRandomAuthor()
{
return new Author { FirstName = "John", LastName = "Wellick" };
}
[Fact]
public void CreateAuthor_RedirectsRoute_201()
{
//Arrange
var mockRepo = new Mock<IAuthorRepository>();
var createAuthor = GetRandomAuthor();
mockRepo.Setup(setup => setup.Add(It.IsAny<Author>())).Verifiable();
var authorController = new AuthorController(mockRepo.Object);
//Act
var result = (CreatedAtRouteResult)authorController.CreateAuthor(createAuthor);
// Assert
Assert.Equal(201, result.StatusCode);
Assert.Equal("GetAuthor", result.RouteName);
}
[Fact]
public void GetAuthor_ReturnsAuthor_200()
{
var mockRepo = new Mock<IAuthorRepository>();
var createAuthor = GetRandomAuthor();
var authorWithId = createAuthor;
authorWithId.Id = 1;
mockRepo.Setup(setup => setup.Get(It.IsAny<int>())).Returns(authorWithId);
mockRepo.Setup(setup => setup.Add(It.IsAny<Author>())).Verifiable();
var authorController = new AuthorController(mockRepo.Object);
authorController.CreateAuthor(createAuthor);
var result = (ObjectResult)authorController.GetById(1);
Assert.Equal(200, result.StatusCode);
Assert.Equal(authorWithId, result.Value);
}
//TODO:: Write Tests for failing causes (I.E no author provided).
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.