Moq Tips 2 - check if a log message with a specific prefix/suffix and call a method with an object having a specific field value

  1. To check if a log message with a specific prefix is logged, you can use Moq's Verify method along with an appropriate assertion.
_logger.Verify(logger => logger.logInformation(
    It.Is<string>(s => s.StartsWith("specific prefix"))), Times.Once);
  1. To verify that a method is called with an object containing a specific property value, you can use Moq's It.Is<T> matcher along with a lambda expression. Here's an example:

    _mockObject.Verify(x => x.MyMethod(It.Is<MyObject>(
     obj => obj.PropertyValue == expectedPropertyValue)), Times.Once);
    
  2. Correctly returns null: Sometimes we need to set up a Moq mock to return null but cannot directly do it as Moq doesn't allow. Please check the following way that you should use:

_bookStoreAccountRepository.Setup(
    b => b.GetBookStoreAccountByUserName(It.IsAny<string>()))
    .Returns((BookStoreAccount)null);

The key is to use (BookStoreAccount)null to explicitly cast null to the expected return type.