Question3r
Question3r

Reputation: 3842

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)

Upvotes: 3

Views: 10561

Answers (1)

Rod Ramírez
Rod Ramírez

Reputation: 1368

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

Upvotes: 6

Related Questions