Three
Three

Reputation: 21

Exception in constructor: Rhino.Mocks.Exceptions.ExpectationViolationException: Expected #0, Actual #1

I had a working Rhino Mock test for this constructor

    public MyClassDataAccess(IMyClassLogger logger)
    {
        _logger = logger ?? throw new ArgumentNullException("logger");
    }

Here's the test

    [TestMethod]
    public void Ctor_ValidParams_CreatesObject()
    {
        // Arrange
        IMyClassLogger logger = MockRepository.GenerateStrictMock<IMyClassLogger>();
        // Act
        var result = new MyClassDataAccess(logger);

        // Assert
        Assert.IsNotNull(result);
    }

Then I modified the constructor to this

    public MyClassDataAccess(IMyClassLogger logger)
    {
        _logger = logger ?? throw new ArgumentNullException("logger");
        _database = new Database(_logger.BaseLogger);
    }

    public Database(ILogger logger)
    {
        _logger = logger ?? throw new ArgumentException(nameof(logger));
        _databaseNameConnectionString = ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString;
    }

Now I get the following error

Message: Initialization method MyClass.Tests.DataAccess.MyClassDataAccessTests.TestInit threw exception. System.Exception: System.Exception: Exception in constructor: Rhino.Mocks.Exceptions.ExpectationViolationException: IMyClassLogger.get_BaseLogger(); Expected #0, Actual #1.

Upvotes: 1

Views: 561

Answers (1)

Nkosi
Nkosi

Reputation: 247631

The exception is thrown because you have called a member on a strict mock

IMyClassLogger logger = MockRepository.GenerateStrictMock<IMyClassLogger>(); //<-- Strict Mock here

that had no expectations defined.

You are invoking

_database = new Database(_logger.BaseLogger);

in the constructor but created no expectation that it was to be called, so you get that ExpectationViolationException on IMyClassLogger.get_BaseLogger() as stated in the exception message

You would need to setup an expectation for that member

[TestMethod]
public void Ctor_ValidParams_CreatesObject()
{
    // Arrange
    ILogger baseLogger =  MockRepository.GenerateMock<ILogger>();
    IMyClassLogger logger = MockRepository.GenerateStrictMock<IMyClassLogger>();
    logger.Stub(_ => _.BaseLogger).Return(baseLogger);

    // Act
    var result = new MyClassDataAccess(logger);

    // Assert
    Assert.IsNotNull(result);
}

Upvotes: 2

Related Questions