简体   繁体   中英

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) .

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.

How would I do this?

Well, it depends on where you instantiate your 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. This will separate the data access from the business logic, which will allow you to unit test both classes more effectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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