我正在进行单元测试。我有一个依赖于多个存储库的控制器(意味着有多个依赖项)。
以下是控制器的代码: -
public class TestController : BaseController
{
//Declaring dependencies
private IProductService _productService;
private IStudenctService _studentService;
private ITeacherService _teacherService;
private IClassService _classService;
private ITaxService _taxService;
private ICategoryService _categoryService;
private ISchoolService _schoolService;
//Constructor calling…
public TestController ()
{
}
public TestController (IProductService productService)
{
this._ productService = productService;
}
public TestController (IStudenctService studenctService)
{
this._ studentService = studenctService;
}
public TestController (ITeacherService teacherService)
{
this._ teacherService = teacherService;
}
public TestController (IClassService classService)
{
this._ classService = classService;
}
public TestController (ITaxService taxService)
{
this._ taxService = taxService;
}
public TestController (ICategoryService categoryService)
{
this._ categoryService = categoryService;
}
public TestController (ISchoolService schoolService)
{
this._ schoolService = schoolService;
}
public TestController (ISchoolService schoolService, ICategoryService categoryService)
{
this._ schoolService = schoolService;
this._ categoryService = categoryService;
}
public TestController (ISchoolService schoolService, ICategoryService categoryService, ITaxService taxService, IClassService classService) {
this._ schoolService = schoolService;
this._ categoryService = categoryService;
this._ taxService = taxService;
this._ classService = classService;
}
}
在上面的代码中,我为每个依赖项创建了单独的构造函数。其中有2个构造函数采用多个参数(依赖arg)。
通过这个我的单元测试方法运行良好。但是当我运行应用程序时它会给我以下错误: -
呃 - 哦,出了点问题!错误代码:500
但是当我只调用一个参数构造函数然后它的工作时。任何人都可以让我知道这里有什么问题吗?在多个依赖项的情况下应该怎么做?
答案 0 :(得分:4)
如果这些是您的类的依赖项,那么您应该有一个构造函数,它将所有依赖项作为参数。
换句话说,如果没有所有依赖项,则无法实例化为有效状态。它们不是可选的,它们是依赖项。
我会从采用这种方法开始,然后问一个单独的问题,如果你的应用程序仍然会抛出错误。