我想为此控制器编写单元测试。我的目标是检查文件是否保存到wwwroot/images
文件夹中,我想通过将文件夹中的文件与Guid
生成的imageNameToSave
.
问题是 - 产生了两个不同Guid
的。
public async Task<IActionResult> Create(CreateNewsViewModel model)
{
var imageNameToSave = Guid.NewGuid() + ".jpg";
var role = await this.newsService.CreateNewsAsync(model.CreatedOn, model.Title, model.Text, imageNameToSave);
using (var ms = new MemoryStream())
{
model.Image.CopyTo(ms);
var uploads =
Path.Combine(this.hostingEnvironment.WebRootPath, "images");
var filePath = Path.Combine(uploads, imageNameToSave);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await model.Image.CopyToAsync(fileStream);
}
}
return this.RedirectToAction("Index", "Home");
}
这是我到目前为止所做的。我的问题是我怎样才能得到相同的结果Guid
并在测试后删除创建的文件?
[TestMethod]
public async Task Call_NewsServiceWithCorrectParams_OnPost()
{
// Arrange
DateTime createdOn = DateTime.Now;
string title = "Tony Stark dies in Avengers!";
string text = "Tony had to sacrifice himself for the greater good in the battle with Tanos";
string imageNameToSave = Guid.NewGuid() + ".jpg";
var ms = new MemoryStream();
var formFile = new FormFile(ms, 0, ms.Length, "name", imageNameToSave);
var newsServiceMock = new Mock<INewsService>();
var hostingEnvironmentMock = new Mock<IHostingEnvironment>();
var currentDirectory = Directory.GetCurrentDirectory();
var endIndex = currentDirectory.IndexOf(@"\MovieManagement\");
var wwwrootFolderPath = "\\MovieManagement\\MovieManagement\\wwwroot";
var path = Path.Combine(currentDirectory.Substring(0, endIndex) + wwwrootFolderPath);
hostingEnvironmentMock.SetupGet(x => x.WebRootPath).Returns(path);
var model = new NewsViewModel()
{
CreatedOn = createdOn,
Title = title,
Text = text,
Image = imageNameToSave
};
newsServiceMock.Setup(ns => ns.CreateNewsAsync(createdOn, title, text, imageNameToSave)).ReturnsAsync(model);
var createModel = new CreateNewsViewModel()
{
CreatedOn = createdOn,
Title = title,
Text = text,
Image = formFile
};
var sut = new NewsManagementController(newsServiceMock.Object, hostingEnvironmentMock.Object);
// Act
var result = await sut.Create(createModel);
// Assert
newsServiceMock.Verify(x => x.CreateNewsAsync(createdOn, title,
text, imageNameToSave), Times.Once);
}