我刚开始进行单元测试。我试着测试一些非常简单的东西:
[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调用封装到实现接口的类中来重构,以使我能够模拟它并验证它是否被调用?
我在用莫克。
发布于 2017-09-15 14:09:15
我是否需要通过将System.IO.File.Delete调用封装到实现接口的类中来重构,以使我能够模拟它并验证它是否被调用?
是
封装实现关注点
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
}它将通过构造函数注入显式地注入到受抚养人中并使用。
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());https://stackoverflow.com/questions/46227992
复制相似问题