【发布时间】:2018-02-20 18:38:58
【问题描述】:
我将人模型类定义为:
public class PersonModel
{
public bool SelectionSubmitted = false;
public bool ShowValidationSummary = false;
public string Name;
public string Get()
{
//actual implementation return some value from the db
return string.Empty;
}
}
控制器实现如下:
class HomeController : Controller
{
[HttpGet]
public ActionResult Index(PersonModel model)
{
if (model.SelectionSubmitted && !ValidateSelections(model))
{
model.ShowValidationSummary = true;
}
return View("Index", model.Get());
}
private bool ValidateSelections(PersonModel model)
{
if(model.Name == "")
{
ModelState.AddModelError("EmptyPersonName", "Person name cannot be null");
}
return ModelState.IsValid;
}
}
测试类和方法定义为:
[TestClass]
public class ChildWithoutPlacementControllerTest
{
private readonly Mock<PersonModel> _mockPersonModel;
public ChildWithoutPlacementControllerTest()
{
_mockPersonModel = new Mock<PersonModel>();
}
[TestMethod]
public void GivenPerson_WhenSearchingForFutureBirthDate_ThenValidationMessageShouldBeShown()
{
//Arrange
HomeController controller = new HomeController();
_mockPersonModel.Setup(x => x.Get()).Returns(It.IsAny<string>());
_mockPersonModel.SetupGet(x => x.Name).Returns(string.Empty);
_mockPersonModel.SetupGet(x => x.SelectionSubmitted).Returns(true);
//Act
controller.Index(_mockPersonModel.Object);
//Assert
var isShowSummarySetToTrue = _mockPersonModel.Object.ShowValidationSummary;
Assert.IsTrue(isShowSummarySetToTrue);
}
}
我想要实现的是将SelectionSubmitted和Name属性分别模拟为true和string.Empty以及SetupGet类的Get方法,并检查测试是否返回对象已将 ShowValidationSummary 设置为 true。
但是,我发现我无法设置非虚拟属性名称。
我做错了什么还是有什么方法可以在不更改实现代码的情况下做到这一点?
【问题讨论】:
-
@nkosi 我猜你发布了一个答案,但现在找不到。它确实帮助这种方法对我很有效。非常感谢!!。
-
我发现了一个问题并正在审查该问题。你真的应该考虑重构你的代码,让它更容易测试。
-
是的,我正在研究如何使它更可测试。 :)
标签: c# asp.net-mvc unit-testing moq