Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assert that method has been called using xUnit

I have a class with a logging method that I want to test. For the example I want to check if the Console.WriteLine method has been called. This is my sample class

public class MyClass
{
    public void LogSomething()
    {
        Console.WriteLine("Test");
    }
}

and its test

public class MyClassTests
{
    [Fact]
    public void LogsSomething()
    {
        MyClass myClass = new MyClass();
            
        myClass.LogSomething(); // Assert that Console.WriteLine has been called once
    }
}

Is there something I can use? (Preferably without additional packages)

I am looking for assertions like this (Pseudo code)

  • Assert.Method(Console.WriteLine).ToHaveBeenCalledWith(myClass.LogSomething);
  • Assert.Method(Console.WriteLine).ToHaveBeenCalledWith(myClass.LogSomething).Times(3); // Check if Console.WriteLine has been called 3 times (loop inside the LogSomething method)
like image 416
Question3r Avatar asked Jul 30 '26 17:07

Question3r


1 Answers

I think you cannot assert that out of the box.

Your best bet is using Moq or another mock framework to do something along this lines. You should always aim for a decoupled logic using dependency injection, otherwise you will end up having a tightly coupled code that is difficult to test and will not be easy to refactor whenever a change in requirements arrives

public interface ILogger
{
    public void Log();    
}
public class Logger: ILogger
{
    public void Log()
    {
        Console.WriteLine("Look mom, i'm logging");
    }
}
public class MyClass
{
    private readonly ILogger Logger
    
    public MyClass(ILogger logger)
    {
        Logger = logger;
    }

    public void MyMethod()
    {
        //other code
        Logger.Log();
    }
}
public class MyClassTests
{
    [Fact]
    public void LogsSomething()
    {
      //arrange
      var logger = new Mock<ILogger>();   
      
      //act
      var sut = new MyClass(logger.Object);
      sut.MyMethod();

      //Assert 
      logger.Verify(foo => foo.Log(), Times.Once()); //here
      //some other assertions
    }
}
like image 117
Rod Ramírez Avatar answered Aug 02 '26 07:08

Rod Ramírez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!