简体   繁体   English

使用Rhino Mocks模拟私有对象调用

[英]Using Rhino Mocks to mock private objects call

So I'm just getting used to mocking stuff. 所以我只是习惯于嘲笑东西。 I have this private variable here: 我在这里有这个私有变量:

private CoreDataContext _coreDataManager;

On this class: 在这个班上:

public class RatesControlReport
        : Chatham.Panda.Batch.ProcessDefinition.BatchProcess

This class has a void method on it that I want to test called CheckSwaptionVols(DateTime runDate) . 该类具有一个我想测试的void方法,称为CheckSwaptionVols(DateTime runDate)

In the first part of my test I can instantiate the main class: 在测试的第一部分中,我可以实例化主类:

RatesControlReport ratesControlReportProcess;
            ratesControlReportProcess = new RatesControlReport();

And basically I want to make this call: 基本上我想打这个电话:

ratesControlReportProcess.CheckSwaptionVols(DateTime.Now);

However this method uses the private variable like so: 但是,此方法使用私有变量,如下所示:

System.Data.Linq.ISingleResult<CheckSwaptionVols> swaptionStatusResult = _coreDataManager.CheckSwaptionVols(this._runDate);

I'd love to be able to pass in a mocked version of this variable instead and return my own specified System.Data.Linq.ISingleResult<CheckSwaptionVols> so the test can continue without a dependency on the DB. 我希望能够传入该变量的System.Data.Linq.ISingleResult<CheckSwaptionVols>版本,并返回我自己指定的System.Data.Linq.ISingleResult<CheckSwaptionVols>以便测试可以继续进行而无需依赖数据库。

How would I do this? 我该怎么做?

Well, it depends on where you instantiate your CoreDataContext. 好吧,这取决于您在哪里实例化CoreDataContext。 If this is constructed in a static context, or in the constructor, there's really no way to create a mock for it. 如果是在静态上下文中或在构造函数中构造的,则实际上没有办法为其创建模拟。 This is why it is generally considered bad practice to instantiate dependencies inside the object. 这就是为什么在对象内部实例化依赖关系通常被认为是不好的做法的原因。 What you need to do is provide some method of dependency injection. 您需要做的是提供某种依赖注入的方法。 This can be as simple as an overloaded constructor: 这可以像重载的构造函数一样简单:

public RatesControlReport(CoreDataContext context)
{
    _coreDataManager = context;
}

...or even an internal method if you're desperate: ...或者甚至是内部方法(如果您不顾一切):

internal void InjectContext(CoreDataContext context)
{
    _coreDataManager = context;
}

Generally speaking, however, it is considered best practice to always provide your CodeDataContext object when constructing your RatesControlReport. 但是,一般来讲,在构造RatesControlReport时始终提供CodeDataContext对象是最佳实践。 This will separate the data access from the business logic, which will allow you to unit test both classes more effectively. 这会将数据访问与业务逻辑分开,从而使您可以更有效地对两个类进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM