简体   繁体   中英

Prevent void method to being call in a unit test for another method

I'm trying to unit test a method in which another method is being called. In this inner method the db is accessed to persist the data and that's why I'd need to prevent it to be actually called. But the following code doesn't achieve that.

Test

[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
}

Being the Schedule method in the Entry class

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;
}

It's inside this AssignToActionTemplate where I persist some data to the database and that's what I would like to prevent from being called. Is there a way to do so?

Thanks

EDIT:

As per Phil Sandler comment,

In the deferralService's Schedule the entry is fetched from a factory based on the deferralRequest (I add some lines in the code)

You are mocking a concrete class, which is generally difficult in .Net. See ' Is it recommended to mock concrete class .'

If you can create an interface for Entry and make the class under test dependent on the interface instead, it will make testing (via mocking) much easier.

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