断言该方法已使用xUnit

时间:2020-10-29 20:59:31

标签: c# unit-testing xunit

我有一个带有要测试的日志记录方法的类。对于该示例,我想检查是否已调用Console.WriteLine方法。这是我的示例课

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

及其测试

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

我可以使用某些东西吗? (最好没有其他软件包)

我正在寻找这样的断言(伪代码)

  • 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)

1 个答案:

答案 0 :(得分:2)

我认为您不能开箱即用。

您最好的选择是使用Moq或其他模拟框架来执行此操作。 您应该始终以使用依赖注入的去耦逻辑为目标,否则最终将拥有紧密耦合的代码,这些代码很难进行测试,并且一旦需求变化到达时就难以重构

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