我正在尝试编写单元测试来测试控制器的动作之一ShareWorkbook
。如果上述操作发生异常,测试应该检查是否将用户发送到一般错误页面(在Startup.cs
中定义)。但是,由于我的硬编码异常,目前我的单元测试失败。我知道我的测试检查用户是否已重定向到错误页面,但是该异常破坏了单元测试(请参阅下面的异常),是否有一种解决方法,以便忽略异常并通过测试?
这是我的 HomeController 和我要测试的操作:
public class HomeController : Controller
{
...
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ShareWorkbook(string emails, string title, string workbookId)
{
var emailStrArr = Regex.Split(emails, Constants.SplitPattern).ToList();
var workbookShareModel = new WorkbookShareModel
{
WorkbookId = workbookId,
Title = title,
Emails = emailStrArr
};
// check to see if the 'WorkbookShareModel' is valid (takes into account its property DataAnnotation)
if (TryValidateModel(workbookShareModel))
{
try
{
ShareWorkbook(workbookShareModel);
}
catch (Exception e)
{
_logger.LogException(e, e.Message);
throw;
}
}
// return no content to avoid page refresh
return NoContent();
}
private void ShareWorkbook(WorkbookShareModel workbookShareModel)
{
// MOCK SERVICE
_workbookManagementService.ShareWorkbook(workbookShareModel);
}
}
当前,我在MockService
中添加了一个硬编码异常:
public class MockManagementService : IManagementService
{
public void ShareWorkbook(WorkbookShareModel sharedWorkbook)
{
if (string.IsNullOrEmpty(sharedWorkbook.WorkbookId))
throw new Exception("Couldn't share workbook");
}
}
我得到的异常(预期):
System.Exception : Couldn't share workbook
at Project.Test.Services.MockManagementService.ShareWorkbook(WorkbookShareModel sharedWorkbook) in D:\_JustCodeHere\Apps\ProjectCore\ProjectCore.Test\Services\MockManagementService.cs:line 27
那是我的单元测试:
public class HomeControllerTest
{
[Fact]
public void error_page_is_shown_if_exception_occurs_during_workbook_sharing_process()
{
// Arrange
var workbookService = new MockManagementService();
var mockLogger = new Mock<ILogger>();
var controller = new HomeController(null, null, workbookService, mockLogger.Object);
controller.ObjectValidator = new TestingObjectValidator();
// Act
// passing 'null' for the workbookId parameter raises an exception
var result = controller.ShareWorkbook("test@email.com", "workbook title", null);
// Assert
var redirectToActionResult = Assert.IsType<RedirectToActionResult>(result);
Assert.Equal("Error", redirectToActionResult.ActionName);
}
}
这是我设置错误页面的方式:
public class Startup
{
...
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
...
}
}
答案 0 :(得分:0)
我最终将控制器操作中的throw;
调用替换为return RedirectToAction("Error");
。这样,我就可以对用户重定向到这样的页面进行单元测试:
public void error_page_is_shown_if_exception_occurs_during_workbook_sharing_process()
{
// Arrange
var emails = "test@email.com";
var title = "";
// Act
// passing 'null' for the workbookId parameter raises an exception
var result = _controller.ShareWorkbook(emails, title, null);
// Assert
var redirectToActionResult = Assert.IsType<RedirectToActionResult>(result);
Assert.Equal("Error", redirectToActionResult.ActionName);
}