简体   繁体   中英

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.

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

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