我有一个自己制作的基本 Controller ,因此我可以轻松地将数据传递到母版页 View 。然而,这个基本 Controller 将一个服务层传递给它,每次我运行我的单元测试时,这个服务层都会杀死它,因为它试图访问一些数据库内容。
private ServiceLayer service;
public ApplicationController():this(new ServiceLayer())
{
}
public PlannerApplicationController(IServiceLayer serviceS)
{
service= serviceS;
}
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
// some stuff gets called here.
}
服务层首先调用
public ServiceLayer ()
: this(new Repository())
{
}
//DI 有另一个构造函数。
因此,当我运行我的测试并且它转到我的 Controller 时,它继承了这个基本 Controller ,一旦它遇到我的 Controller 构造函数,它似乎就调用了这个基本 Controller 。
所以在我的单元测试中,我尝试通过做这样的事情来模拟基本 Controller
baseController = new ApplicationController(SerivceLayerInterface);
我在 serviceLayer 接口(interface)中使用 moq 和东西来模拟存储库,但它似乎没有效果。
所以不知道该怎么做。
最佳答案
与其模拟你的基础 Controller ,不如模拟服务层接口(interface)。例如,使用 MoQ 你可以这样做:
var serviceMock = new Mock<IServiceLayer>();
//serviceMock.Setup(s => s.SomeMethodCall()).Returns(someObject);
var controller = new BaseController(serviceMock.Object);
一般的想法是,如果你正在测试你的 Controller ,你想模拟它的依赖关系。你想避免 mock 你正在测试的东西。
关于c# - 如何在 asp.net mvc 中模拟基本 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1518017/