我正在尝试对一个调用另一个方法的方法进行单元测试。在这个内部方法中,访问db以保持数据,这就是为什么我需要阻止实际调用它。但是下面的代码没有实现这一点。
测试
[Test]
public void Schedule_WhenEntryIsAvailable()
{
#region Arrange
var entryStub= MockRepository.GenerateStub<Entry>();
_entryDal.Stub(_ => _.Retrieve(Arg<long>.Is.Anything)).Return(entryStub);
entryStub.Stub(_ => _.AssignToActionTemplate(Arg<ActionTemplates>.Is.Anything, Arg<long>.Is.Anything, Arg<IUnitOfWork>.Is.Anything));
#endregion
#region act
//I create the deferralRequest
_deferralService.Schedule(deferralRequest);
#endregion
#region assert
//...
#endregion
}
成为Entry类中的Schedule方法
public virtual void Schedule(DeferralRequestDto deferralRequest, bool ignoreSeasonal = false)
{
if (!deferralRequest.Deferrals.Any()) return;
if (Validate(deferralRequest, ValidationGroup.PersonValidation & ValidationGroup.EntryValidation))
{
foreach (var deferral in deferralRequest.Deferrals)
{
var entryFromRequest= EntryFactory.Factory(_entryDal.Retrieve(deferral.Id));
/.... Do different things
var deferToEntry = CreateDeferralEntry(deferral, deferFromEntry, deferralRequest.UserId);
}
}
}
private Entry CreateDeferralEntry(Deferral deferral, Entry @entry, long userId)
{
var deferFromEntry = @entry.GetGentleEntity(); //We're using Gentle as persistent framework
var deferEntry = new entry
{
//We populate the deferEntry using the deferFromEntry fetched and the deferral from the parameters
};
//And after a few thing we call this method that actually persist to the an action table in the db which is the bit I would like to avoid being called
deferToEntry.AssignToActionTemplate(ActionTemplates.Deferral, deferEntry.CreatedBy, null);
return deferToEntry;
}
在这个AssignToActionTemplate中,我将一些数据保存到数据库中,这就是我想要阻止它被调用的内容。有办法吗?
由于
编辑:
根据Phil Sandler的评论,
在deferralService的Schedule中,根据deferralRequest从工厂中获取条目(我在代码中添加了一些行)
答案 0 :(得分:1)
你正在嘲笑一个具体的课程,这在.Net中通常很难。请参阅“Is it recommended to mock concrete class。”
如果您可以为Entry创建一个接口并使受测试的类依赖于接口,那么它将使测试(通过模拟)变得更加容易。