c# - 如何为具有两个参数的Controller方法编写单元测试以及需要测试哪些场景?
问题描述
我是单元测试的新手。我想为删除控制器操作编写单元测试。我想使用 NSubstitute 来模拟所有依赖项。当前的实现使用接口 IRepository 来抽象出对底层数据源的调用。
控制器
public ActionResult Delete(string fileName, bool isPublic)
{
try
{
repo.DeleteDocument(new PortalDocument
{
Path = fileName,
IsPublic = isPublic
});
}
catch (Exception e)
{
EventLog.Logger.LogCritical(e, e.Message);
}
return RedirectToAction(IndexViewName);
}
存储库的接口。
public interface IRepository<out T> where T:
CloudBlobContainer
{
bool DeleteDocument(PortalDocument document);
}
PortalDocument 类
public class PortalDocument
{
public bool IsPublic { get; set; }
}
提前致谢。
解决方案
我想你已经找到了快乐的路径场景,测试没有例外时会发生什么。但是现在您需要测试不愉快的路径,当抛出异常时它的行为是否正确。
//arrange
var mockRepo = new Mock<DocumentRepository>(MockBehavior.Strict);
mockRepo.Setup(r => r.DeleteDocument(It.IsAny<PortalDocument>())).Throws(new Exception("test"));
var controller = new DocumentController(mockRepo.Object);
//act
var result = controller.Delete("filename", true);
//assert
//make sure result is a redirect result
//but how do I test that it got logged?
不幸的是,您会发现您实际上无法测试您记录的内容。为什么?因为你有一个静态方法调用。静态方法调用是不可测试的。相反,您应该遵循依赖倒置原则。
解决此问题的一种方法是使用可注入的东西来包装您的日志记录调用。
public interface ILogger
{
void LogCritical(Exception exception);
}
public class EventLogLogger : ILogger
{
public void LogCritical(Exception exception)
{
EventLog.Logger.LogCritical(exception, exception.Message);
}
}
然后你的单元测试变成:
//arrange
var mockRepo = new Mock<IDocumentRepository>(MockBehavior.Strict);
mockRepo.Setup(r => r.DeleteDocument(It.IsAny<PortalDocument>())).Throws(new Exception("test"));
var mockLogger = new Mock<ILogger>(MockBehavior.Strict);
mockLogger.Setup(l => l.LogCritical(It.IsAny<Exception>())).Verifiable;
var controller = new DocumentController(mockRepo.Object, mockLogger.Object);
//act
var result = controller.Delete("filename", true);
//assert
//make sure result is a redirect result
mockLogger.Verify();
请注意,我在示例中使用了Moq 库语法。您需要根据您的模拟框架进行调整。
如果您是依赖注入的新手,我强烈建议您观看Miguel Castro 的 Deep Dive Into Dependency Injection 和 Writing Quality Decoupled Code。
推荐阅读
- git - 如何将远程分支合并到本地分支?
- python - Python:ValueError: scatter 需要 y 列为数字?
- java - 获取 org.apache.maven.plugins:maven-jar-plugin:2.3.2 或其依赖项之一无法解决错误
- c - 以某些数字打印数字
- python - “break”会杀死一个运行while循环的线程吗?
- python - 使用多列的 Pandas groupby 函数
- python-3.x - flask-sqlalchemy db.Model._decl_class_registry.values() 和 db.metadata.tables 不一致
- libgdx - libgdx 音乐兼容性
- mysql - 如何将同一张表中的 SUM() 和 COUNT() 表更新到不同的列
- python - Order by 有时在我的查询中不起作用