public static class LoggerHelper { public static Mock<ILogger<T>> LoggerMock<T>() where T : class { return new Mock<ILogger<T>>(); } public static void VerifyLog<T>(this Mock<ILogger<T>> loggerMock, LogLevel level, string containMessage, Times times) { loggerMock.Verify( x => x.Log( level, It.IsAny<EventId>(), It.Is<It.IsAnyType>((o, t) => o.ToString().Contains(containMessage)), It.IsAny<Exception>(), (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), times); } public static void VerifyLog<T>(this Mock<ILogger<T>> loggerMock, LogLevel level, Times times) { loggerMock.Verify( x => x.Log( level, It.IsAny<EventId>(), It.IsAny<It.IsAnyType>(), It.IsAny<Exception>(), (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), times); } }
利用要领
[Fact] public void Echo_ShouldLogInformation() { // arrange var mockLogger = LoggerHelpe.LoggerMock<UserController>(); var controller = new UserController(mockLogger.Object); // act controller.Echo(); // assert mockLogger.VerifyLog(LogLevel.Information, "hello", Times.Once()); }
7. 拓展 7.1 TDD先容TDD是测试驱动开拓(Test-Driven Development)的英文简称. 一般是先提前设计好单位测试的各类场景再举办真实业务代码的编写,编织安详网以便将Bug抹杀在在摇篮状态。
此种开拓模式以测试先行,对开拓团队的要求较高, 落地大概会存在许多实际坚苦。具体说明可以参考如下
https://www.guru99.com/test-driven-development.html
参考链接https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices
https://github.com/AutoFixture/AutoFixture
到此这篇关于浅谈.Net Core后端单位测试的实现的文章就先容到这了,更多相关.Net Core 单位测试内容请搜索剧本之家以前的文章或继承欣赏下面的相关文章但愿各人今后多多支持剧本之家!
您大概感乐趣的文章: