1
我試圖測試接受視圖模型並創建一個新條目的控制器動作。這裏是控制器動作:單元測試MVC 5控制器使用工作單元和知識庫創建動作
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ContactViewModel viewModel)
{
if (!ModelState.IsValid)
return View("Create", viewModel);
_unitOfWork.Contacts.Add(Mapper.Map(viewModel, new Contact()));
_unitOfWork.Complete();
return RedirectToAction("Index");
}
而且單元測試:
[TestClass]
public class ContactControllerTests
{
private ContactsController _controller;
private Mock<IContactRepository> _mockRepository;
private string _userId;
private Mock<IUnitOfWork> _mockUoW;
[ClassInitialize]
public static void Init(TestContext context)
{
Mapper.Initialize(c => c.AddProfile<MappingProfile>());
}
[TestInitialize]
public void TestInitialize()
{
_userId = "1";
_mockRepository = new Mock<IContactRepository>();
_mockUoW = new Mock<IUnitOfWork>();
_mockUoW.SetupGet(u => u.Contacts).Returns(_mockRepository.Object);
_controller = new ContactsController(_mockUoW.Object);
_controller.MockCurrentUser(_userId, "[email protected]");
}
[TestMethod]
public void CreatePost_ValidValuesSubmitted_ShouldCallComplete()
{
var viewModel = new ContactViewModel()
{
FirstName = "a",
LastName = "b"
};
_controller.Create(viewModel);
_mockRepository.Object.GetContacts(_userId).Should().HaveCount(1);
}
}
,而我希望它是1單元測試總是返回計數0我非常新的TDD和我實現工作單位和存儲庫模式,如Mosh Hamedani的課程所示: https://app.pluralsight.com/library/courses/full-stack-dot-net-developer-architecture-testing/table-of-contents
如果您試圖測試已經寫好的代碼片段,它不是TDD(測試*驅動*)。 –