我是单元测试新手。我正在尝试测试一些非常简单的东西:
[HttpPost]
public ActionResult EditProfile(ProfileViewModel model)
{
if (ModelState.IsValid)
{
// Retrieve current user
var userId = User.Identity.GetUserId();
var user = _dataRepository.GetUserById(userId);
//If it isn't the single-instance default picture, delete the current profile
// picture from the Profile_Pictures folder
if (!String.Equals(user.ProfilePictureUrl, _defaultPic))
System.IO.File.Delete(Server.MapPath(user.ProfilePictureUrl));
在这部分代码中,我创建了一个条件,该行将计算为 true:
if (!String.Equals(user.ProfilePictureUrl, _defaultPic))
我想验证是否调用了System.IO.File.Delete
。
执行此操作的最佳方法是什么?
我是否需要通过将 System.IO.File.Delete
调用包装在我自己的实现接口(interface)的类中进行重构,以便我可以模拟它并验证它是否被调用?
我正在使用起订量。
最佳答案
Do I need to refactor by wrapping the System.IO.File.Delete call in my own class that implements an interface so that I can mock it and verify that it was called?
是的
封装实现问题
public interface IFileSystem {
void Delete(string path);
//...code removed for brevity
}
public class ServerFileSystemWrapper : IFileSystem {
public void Delete(string path) {
System.IO.File.Delete(Server.MapPath(path));
}
//...code removed for brevity
}
它将通过构造函数注入(inject)显式注入(inject)到依赖项中并使用。
if (!String.Equals(user.ProfilePictureUrl, _defaultPic))
_fileSystem.Delete(user.ProfilePictureUrl); //IFileSystem.Delete(string path)
现在允许根据需要设置和验证模拟
//Arrange
var mockFile = new Mock<IFileSystem>();
var profilePictureUrl = "...";
//...code removed for brevity
var sut = new AccountController(mockFile.Object, ....);
//Act
var result = sut.EditProfile(model);
//Assert
result.Should().NotBeNull();
mockFile.Verify(_ => _.Delete(profilePictureUrl), Times.AtLeastOnce());
关于c# - 验证 File.Delete 是否已使用 Moq 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46227992/