Reputation: 28326
I'm starting a new project from scratch. Currently I'm working through design of some elements and attempting to implement unit testing early on. The problem, the unit tests are failing due to what appears to be a null response from a controller action. In the Watch Window, actionResult
displays "Internal error in the expression evaluator" and contentResult
is null.
How do I fix this?
xunit 2.2.0.3545, Moq 4.7.63.0
Here is the unit test (xunit):
// Used in the unit tests
private List<City> cities = new List<City>
{
new City { City_Name = "Chicago", City_Code = 1 },
new City { City_Name = "New York", City_Code = 2 },
new City { City_Name = "Seattle", City_Code = 3 }
};
[Fact]
public async Task Get_AllCities_PropertiesArePopulated()
{
// Arrange
var mockService = new Mock<ICityService>();
mockService.Setup(x => x.GetCities()).ReturnsAsync(this.cities);
var controller = new CityController(mockService.Object);
// Act
IHttpActionResult actionResult = await controller.GetCities();
var contentResult = actionResult as OkNegotiatedContentResult<List<City>>;
foreach (var city in contentResult.Content)
{
// doesn't get here due to .Content being null.
}
}
Here is my controller:
public class CityController : ApiController
{
private readonly ICityService cityService;
public CityController(ICityService svc)
{
this.cityService = svc;
}
public async Task<IHttpActionResult> GetCities()
{
var cities = await this.cityService.GetCities();
if (!cities.Any())
{
return this.BadRequest();
}
return this.Ok(cities);
}
}
The service interface:
public interface ICityService
{
Task<IEnumerable<City>> GetCities();
}
Upvotes: 1
Views: 1086
Reputation: 247213
GetCities
return IEnumerable<City>
Task<IEnumerable<City>> GetCities();
but in the cast of the test you cast it to the wrong type using List<City>
var contentResult = actionResult as OkNegotiatedContentResult<List<City>>;
When you should be using IEnumerable<City>
var contentResult = actionResult as OkNegotiatedContentResult<IEnumerable<City>>;
Upvotes: 3