使用NUnit模拟c#构造函数
本文关键字:构造函数 模拟 NUnit 使用 | 更新日期: 2023-09-27 18:12:50
我有以下c#构造函数,我想模拟(使用NUnit+RhinoMocks):
public SMin(Dictionary<string, string> conf) : base(conf)
{
dat = Mgmt.Getbit<bool>(conf["D_BIT"]);
avg = Mgmt.Getbit<bool>(conf["A_BIT"]);
}
我试了如下:
我正在为构造函数中初始化的变量(dat & avg
)创建Mgmt类,SMin和对象的模拟。现在,我如何模拟构造函数,测试它并将构造函数中初始化的dat and avg
分配给我为单元测试创建的模拟对象(_dat & _avg
)。
[TestFixture()]
class SMinUTest
{
[TestFixtureSetUp]
public void Setup()
{
var _mockMgmt = MockRepository.GenerateMock<Mgmt>();
var _smin = MockRepository.GenerateStrictMock<SMin>(null);
var _dat = MockRepository.GenerateMock<IF_IO<bool>>();
var _avg = MockRepository.GenerateMock<IF_IO<bool>>();
}
...
...
}
您需要通过构造函数将Mgmt实例传递给SMin。忽略基类,SMin看起来像这样:
class SMin
{
// Just guessing at what type Mgmt is.. replace with your actual class name
Management mgmt; // Instance passed in via constructor
public SMin(Dictionary<string, string> conf, Management mgmt)
{
this.mgmt = mgmt;
dat = mgmt.Getbit<bool>(conf["D_BIT"]);
avg = mgmt.Getbit<bool>(conf["A_BIT"]);
}
// Other code
}
测试可能看起来像这样:
[Test]
public void MyTest()
{
var conf = new Dictionary<string, string>();
var _mockMgmt = MockRepository.GenerateMock<Management>();
// TODO - Set expectations on _mockMgmt here, since the SMin constructor uses it
// Create instance of SMin, passing in our mock
var smin = new SMin(conf, _mockMgmt);
// TODO - More test code, followed by assertions
}