我正在努力测试以下方法:
public JsonResult GetJsonObjectsFromOffices(int siteId)
{
IEnumerable<Office> officeList;
officeList = repository.Offices
.Where(o => o.SiteID == siteId)
.OrderBy(o => o.Name);
return Json(new SelectList(officeList, "OfficeID", "Name"));
}
使用Moq和xUnit,我有以下测试
//Arrange
Mock<IFormRepository> mockRepo = new Mock<IFormRepository>();
var mockUserMgr = GetMockUserManager();
var userValid = new CustomUserValidator();
var passwordValid = new CustomPasswordValidator();
var passwordHash = new PasswordHasher<AppUser>();
mockRepo.Setup(m => m.Offices).Returns(new Office[]
{
new Office {OfficeID = 2, SiteID = 2, Name = "Bravo"},
new Office {OfficeID = 1, SiteID = 1, Name = "Alpha"},
new Office {OfficeID = 3, SiteID = 1, Name = "Charlie"}
}.AsQueryable<Office>());
AdminController controller = new AdminController(mockUserMgr.Object, userValid, passwordValid, passwordHash, mockRepo.Object);
//Act
var jsonObj = controller.GetJsonObjectsFromOffices(1);
//'Unexpected character encountered while parsing value: M. Path '', line 0, position 0.' error on line below
//var selectList = JsonConvert.DeserializeObject(jsonObj.Value.ToString());
测试的Assert部分的目标是验证是否返回了正确数量的列表项(即两个项目对应SiteID = 1
)。
jsonObj
是JsonResult
类型,其值为{Microsoft.Mvc.Rendering.SelectList}
。在SelectList
内,生成了正确的Items
,但我不知道如何访问它们来计算
答案 0 :(得分:2)
结果中存储的值将是传递给它的类型。
将期望值转换为期望的类型,并在成功转换时对其执行断言
//...code removed for brevity
//Act
var jsonResult = controller.GetJsonObjectsFromOffices(1);
//Assert
var selectList = jsonResult.Value as SelectList;
Assert.NotNull(selectList); //<-- cast was successful
var expected = 2;
var actual = selectList.Count();
Assert.Equal(expected, actual);