【发布时间】:2019-09-30 08:39:32
【问题描述】:
我想用 C#(使用 NUnit)编写一些单元测试,但我不知道如何继续。
所以我有一个类,它呈现一个用户模型,DataModel 具有四个属性。我在我的 ExcelInit 构造函数中发送这个模型。
DataModel dm = new DataModel();
dm.PopulateDataModel(holder);
ExcelInit d1 = new ExcelInit(dm);
d1.BeginProcess();
然后在 BeginProcess 我开始我的实际方法。
public class ExcelInit
{
public DataModel _model { get; set; }
public ExcelInit(DataModel model)
{
_model = model;
}
public void BeginProcess()
{
DataReader dr = new DataReader();
CellLocation cl = new CellLocation();
//Gets the corresponding cellAddress for the cell that contains "2x5" from our hidden config-sheet
var correspondingCellsAddress = cl.FindCorrespondingCellAddress(_model.boxSize);
//returns the range that we need to copy i.e. the whole range of the box ala B3:AG13
var srcRange = dr.GetRangeForSourceDestination(correspondingCellsAddress);
//Last row of sheet 6 (the sheet we populate) with input-boxes
var lastRow = dr.FindLastRowByName("Your_Data_Sheet") + 3;
//gets the cell we'll copy our range to
var destRange = "B" + lastRow.ToString();
DataHandler dh = new DataHandler();
dh.CopyBox(srcRange, destRange, _model);
}
但是正如你所看到的,我在 BeginProcess 中创建了很多类,我的老师告诉我不能这样做(我需要使用 DI 才能进行测试)。但我的问题是,当我需要在我的方法中使用这么多类时,我该如何使用 DI?还是我的方法错了,我不应该依赖这么多不同的东西?
【问题讨论】:
-
好吧,您可以将
DataReader作为参数注入您的方法,而不是在内部创建它。这同样适用于您的DataHandler。但除此之外,我在这里看不到太多可注入的东西。您的老师具体指的是哪些课程? -
没什么特别的,他只是总是告诉我(使用接口将类注入构造函数而不是创建新关键字)所以我可以创建测试但我只是不明白我是否需要不使用任何新关键字和只需将 DataReader、DataHandler 和 CellLocation 放入 DI,但如果是这样,我是否需要在调用此方法的类中创建新实例?然后我仍然使用 new 关键字,然后我无法测试
-
@8329396 因为你应该依赖抽象(接口)而不是特定的实现,当你依赖抽象时,你可以创建一个模拟并定义假行为。总结一下,在创建 ExcelInit 时使用 new,但在构造函数中使用接口,以便以后可以使用 Mock
-
"在调用此方法的类中创建新实例?"没错,这就是你应该做的。 DI 的重点不是 if 您使用
new(即使是 DI 容器也必须以某种方式创建实例,无论是通过反射还是使用new(...)),而是 where。因此,在您的测试方法中,您创建了依赖项 - 例如阅读器 - 因此您可以在被测系统中简单地使用它们,而不是在那里创建它们。 -
这是您需要与老师进行的讨论。所以不应该是你的第一站。去和他/她谈谈,寻求一个例子或一些真正的指导。然后你就会知道该怎么做。这里没有人能猜出你的老师的意思/期望。去问问。
标签: c# unit-testing dependency-injection