У меня есть этот метод тестирования для тестирования контроллера API, который возвращает строку JSON для ненулевого ответа.
[TestClass]
public class TransactionsTests
{
[TestMethod]
public void ColorPerformance_GetChartData_NotNullResponse_Test()
{
// Arrange
string quality = null, cars = null, year = "2015";
var listColorPerformanceChartData = new List<ColorPerformanceChartData>();
var mockRepository = new Mock<IColorPerformanceRepository>();
mockRepository.Setup(x => x.GetChartData(quality, cars, year))
.Returns(listColorPerformanceChartData);
var controller = new ColorPerformanceController(mockRepository.Object);
// Act
IHttpActionResult actionResult = controller.GetChartData(quality, cars, year);
var contentResult = actionResult as OkNegotiatedContentResult<object>;
// Assert
Assert.IsNotNull(contentResult);
Assert.IsNotNull(contentResult.Content);
}
}
Этот тест проходит в том, что contentResult
не равно нулю. Однако я не уверен, что тест написан правильно по следующим причинам:
contentResult.Content
имеет пустые данные в том смысле, что данные не возвращаются из метода_repository.GetChartData()
, но он не пуст, потому что все же построенный json выглядит следующим образом:
{ categories = {int[0]}, series = { name = "Number of colors", data = {double[0]} } }
contentResult.ContentNegotiator
,contentResult.Formatter
иcontentResult.Request
выдают исключениеInvalidOperationException
с сообщениемHttpControllerContext.Configuration must not be null.
Я не знаю, почему это происходит.
Контроллер API:
public class ColorPerformanceController : ApiController
{
private IColorPerformanceRepository _repository;
public ColorPerformanceController(IColorPerformanceRepository repository)
{
_repository = repository;
}
public IHttpActionResult GetChartData(string quality, string cars, string year)
{
try
{
var data = ProcessData(quality, cars, year);
return Ok(data);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
private object ProcessData(string quality, string cars, string year)
{
var data = _repository.GetChartData(quality, cars, year);
return new {
categories = data.Select(d => d.Id).ToArray(),
series = new[] { new { name = "Number of colors", data = data.Select(d => d.CumulativePercentage).ToArray() }}
};
}
}
IColorPerformanceRepository:
public interface IColorPerformanceRepository
{
IEnumerable<ColorPerformanceChartData> GetChartData(string quality, string cars, string year);
}
Объект, возвращенный из реализации репозитория:
public class ColorPerformanceChartData
{
private double _cumulativePercentage;
public double CumulativePercentage {
get { return Math.Round(_cumulativePercentage, 2); }
set { _cumulativePercentage = value; }
}
public int Id { get; set; }
}
Что я здесь упускаю или делаю неправильно?
_repository.GetChartData()
. Это потому, что я просто издеваюсь над поведением или я должен получить данные? - person Animesh   schedule 10.07.2015...and contentResult.Request all are throwing an exception of InvalidOperationException...
- person DLeh   schedule 10.07.2015_repository.GetChartData()
, но потом понял, что MockRepository на самом деле не вызывает фактический метод репозитория. - person Animesh   schedule 10.07.2015