Search code examples
c#rhino-mocksrhino

Can't figure out why this Rhino Mock is failing? Error: Expected True, But Was: False


Here is the code:

public interface IAccessPoint
{
    int BackHaulMaximum { get; set; }

    bool BackHaulMaximumReached();
    void EmailNetworkProvider();
}

public class AccessPoint : IAccessPoint
{

    public int BackHaulMaximum { get; set; }

    public bool BackHaulMaximumReached()
    {
        if (BackHaulMaximum > 80)
        {
            EmailNetworkProvider();
            return true;
        }
        return false;
        }

    public void EmailNetworkProvider()
    {

    }
}

//Test
[Test]
public void NetworkProviderShouldBeEmailedWhenBackHaulMaximumIsReached()
{
        var apMock = MockRepository.GenerateMock<IAccessPoint>();

        apMock.Stub(x => x.BackHaulMaximum).Return(81);

        Assert.AreEqual(true, apMock.BackHaulMaximumReached());

        apMock.AssertWasCalled(x => x.EmailNetworkProvider());
 }

Solution

  • You shouldn't be mocking the class that you are testing. You should only be mocking the classes that class under test depends on. Something like this:

    public interface IAccessPoint
    {
        int BackHaulMaximum { get; set; }
    
        bool BackHaulMaximumReached();
        void EmailNetworkProvider();
    }
    
    public class AccessPoint : IAccessPoint
    {
        private IMailProvider Mailer { get; set; }
    
        public AccessPoint( IMailProvider provider )
        {
            this.Mailer = provider ?? new DefaultMailProvider();
        }
    
        public int BackHaulMaximum { get; set; }
    
        public bool BackHaulMaximumReached()
        {
            if (BackHaulMaximum > 80)
            {
                EmailNetworkProvider();
                return true;
            }
            return false;
            }
    
        public void EmailNetworkProvider()
        {
            this.Mailer.SendMail(...);
        }
    }
    
    [Test]
    public void NetworkProviderShouldBeEmailedWhenBackHaulMaximumIsReached()  
    {  
        var mailerMock = MockRepository.GenerateMock<IMailProvider>();  
    
        mailerMock .Expect( m => m.SendMail( ... specify argument matches ... ) ); 
    
        var accessPoint = new AccessPoint( mailerMock ); 
    
        accessPoint.BackHaulMaximum = 81;
    
        Assert.IsTrue( accessPoint.BackHaulMaximumReached() );
    
        mailerMock.VerifyAllExpectations();
    }