我知道这可能是基本的东西,但如果我有一个在构造函数中初始化的私有字段集合,例如
public blah()
{
_brushes = new List<Brush> { Brushes.Red, Brushes.Blue, Brushes.Green };
}
然后我有一个方法可以设置它(但也可以做很多其他事情)例如
public CreateModel(){
// does stuff
_model.Brush = GetNextBrush();
// does stuff
}
然后是私有方法,例如
private Brush GetNextBrush()
{
var brush = _brushes[_index];
_index++;
if (_index == _brushes.Count)
{
_index = 0;
}
return brush;
}
对其进行单元测试的适当方法是什么?将画笔提取到具有接口的服务中并将其传递到构造函数中?看起来有点矫枉过正,但我可能错过了一些东西。我不想公开该方法 - 似乎是错误的。
非常感谢
-杰妮
更大的摘录:
public class vm : IViewModel
{
private readonly List<Brush> _brushes;
private int _brushIndex;
private readonly _modelCollection;
public vm(IModelCollection modelCollection)
{
_modelCollection = modelCollection;
_brushes = new List<Brush> { Brushes.Red, Brushes.Blue, Brushes.Green };
}
public void AddSig(ISigModel sigModel)
{
_model.Brush = GetNextBrush();
if (sigModel.IsAtt)
{
sigModel.Process = "StartEvent";
}
_modelCollection.AddSig(sigModel);
StartCSUpdatingEvent();
}
private Brush GetNextBrush()
{
var brush = _brushes[_index];
_index++;
if (_index == _brushes.Count)
{
_index = 0;
}
return brush;
}
}
解决方案是将
GetNextBrush()
移至一个单独的类中,该类只有一个职责:生成下一个画笔。
public class BrushGenerator
{
private List<Brush> _brushes = new List<Brush> { Brushes.Red, Brushes.Blue, Brushes.Green };
private int _index = 0;
public Brush GetNextBrush()
{
var brush = _brushes[_index];
_index++;
if (_index == _brushes.Count)
{
_index = 0;
}
return brush;
}
}
在包含
CreateModel()
的类中,您可以创建此类的实例:
private BrushGenerator _brushGenerator = new BrushGenerator();
public CreateModel(){
// does stuff
_model.Brush = _brushGenerator .GetNextBrush();
// does stuff
}
现在您可以为您的
BrushGenerator
类编写单元测试:
[DataRow(1, Brushes.Red)]
[DataRow(2, Brushes.Blue)]
[DataRow(3, Brushes.Green)]
[DataRow(4, Brushes.Red)]
[DataTestMethod]
public void CorrectBrushIsReturned(int times, Brushes expectedBrush)
{
var brushGenerator = new BrushGenerator();
Brushes result = Brushes.None;
for(int i = 0; i < times; i++)
{
result = brushGenerator.GetNextBrush();
}
Assert.AreEqual(expectedBrush, result);
}