Skip to content

Instantly share code, notes, and snippets.

@safestudent
Created December 4, 2018 12:15
Show Gist options
  • Save safestudent/582353103f33afdd9ff6720ded949b26 to your computer and use it in GitHub Desktop.
Save safestudent/582353103f33afdd9ff6720ded949b26 to your computer and use it in GitHub Desktop.
SprintsControllerTest
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SprintTracker.Web.Controllers;
using SprintTracker.Web.Models;
using System.Threading.Tasks;
using Xunit;
namespace SprintTracker.Tests
{
public class SprintsControllerTest
{
/* Our test below will simply confirm that the `Index` method in the `SprintsController`
* class returns a `View` For a more complicated test(e.g.the `Create` method in the
* controller) you would simply pass through a `sprint` object (containing test data)
* to the method and then confirm that the data had been passed on to the `View` by
* asserting that the `result.ViewData.Sprint.SprintName` was the same as the
* `sprint.SprintName` property in the original sprint object containing the test data.
* However, this would be considered an `Integration Test`.*/
// Alt + Enter to import Task from 'System.Threading'
// The 'controller' effectively functions as an API, which is why it is labelled as an
// 'async' task - delays over the internet mean that we can't wait for one method call to
// finish before we start a new one.
[Fact]
public async Task Index_ReturnsAViewResult()
{
// ARRANGE: Set up 'in memory' database and initialise our controller
// You need to set up the Microsoft.EntityFrameworkCore.InMemory libraryas a dependency
// through NuGet for DbContextOptionsBuilder to work, then Alt + Enter once installed
// SprintTrackerWebContext is our context file from the Web project (under Data)
var options = new DbContextOptionsBuilder<SprintTrackerWebContext>()
.UseInMemoryDatabase(databaseName: "Add_writes_to_database")
.Options;
// Now set up our context
var _dbContext = new SprintTrackerWebContext(options);
// Then pass it through to our controller (alt + enter to import controller from Web)
var controller = new SprintsController(_dbContext);
// ACT: call the index method in the controller
// We need to import Microsoft.AspNetCore.Mvc.Abstractions and ViewFeatures
// (first download the library using NuGet) for the IActionResult and ViewResult
// to be recognised
var result = await controller.Index();
// ASSERT: Check that a `View` is returned.
// Alt+ enter to import ViewResult
var viewResult = Assert.IsType<ViewResult>(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment