Logo video2dn
  • Сохранить видео с ютуба
  • Категории
    • Музыка
    • Кино и Анимация
    • Автомобили
    • Животные
    • Спорт
    • Путешествия
    • Игры
    • Люди и Блоги
    • Юмор
    • Развлечения
    • Новости и Политика
    • Howto и Стиль
    • Diy своими руками
    • Образование
    • Наука и Технологии
    • Некоммерческие Организации
  • О сайте

Скачать или смотреть How to Pass ILogger to Static Classes for Unit Testing in C#

  • vlogize
  • 2025-05-25
  • 3
How to Pass ILogger to Static Classes for Unit Testing in C#
How do I pass ILogger to a static class so it's suitable for unit tests as wellc#.netloggingilogger
  • ok logo

Скачать How to Pass ILogger to Static Classes for Unit Testing in C# бесплатно в качестве 4к (2к / 1080p)

У нас вы можете скачать бесплатно How to Pass ILogger to Static Classes for Unit Testing in C# или посмотреть видео с ютуба в максимальном доступном качестве.

Для скачивания выберите вариант из формы ниже:

  • Информация по загрузке:

Cкачать музыку How to Pass ILogger to Static Classes for Unit Testing in C# бесплатно в формате MP3:

Если иконки загрузки не отобразились, ПОЖАЛУЙСТА, НАЖМИТЕ ЗДЕСЬ или обновите страницу
Если у вас возникли трудности с загрузкой, пожалуйста, свяжитесь с нами по контактам, указанным в нижней части страницы.
Спасибо за использование сервиса video2dn.com

Описание к видео How to Pass ILogger to Static Classes for Unit Testing in C#

Discover how to efficiently pass `ILogger` to static classes in C# for robust unit testing with practical examples and solutions.
---
This video is based on the question https://stackoverflow.com/q/72391109/ asked by the user 'nop' ( https://stackoverflow.com/u/13677853/ ) and on the answer https://stackoverflow.com/a/72391571/ provided by the user 'Mykhailo Nohas' ( https://stackoverflow.com/u/3671757/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: How do I pass ILogger to a static class, so it's suitable for unit tests as well

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
How to Pass ILogger to Static Classes for Unit Testing in C#

Unit testing can often be tricky, especially when dealing with static classes in C# . One common problem developers face is how to pass dependencies like ILogger into a static class. In this post, we'll dive into how to correctly pass an ILogger instance to a static class, ensuring that our code remains testable and maintainable.

The Problem

Let's say you have a static class, Policies, with a static method RateLimit(...) that takes an ILogger<T> as a parameter—this is necessary for logging during its operations. However, you want to test this functionality, but passing an instance of ILogger<T> can be challenging in a static context.

In your unit test, you may encounter issues with compile-time errors when trying to pass NullLogger.Instance, a common practice that doesn't work seamlessly in this case. Here's a basic outline of how this situation arises:

Example Code Structure

Consider the following simplified version of your classes:

[[See Video to Reveal this Text or Code Snippet]]

In the PoliciesTests class, you initially tried to execute the RateLimit method like this:

[[See Video to Reveal this Text or Code Snippet]]

This leads to a compile-time error since NullLogger.Instance doesn't provide the expected type.

The Solution

Using NullLoggerFactory

To resolve this issue, we can utilize the NullLoggerFactory, which allows us to create an instance of ILogger<T> that can be passed to our static methods without any runtime or compile-time issues.

Step-by-Step Implementation

Import Microsoft.Extensions.Logging.Abstractions:
Ensure you have the necessary package to access NullLoggerFactory.

Create a Logger Instance in Tests:
Use NullLoggerFactory.Instance.CreateLogger<T>() to create a logger instance specifically for your test class.

Here’s how the updated PoliciesTests class looks with the new logger instance:

[[See Video to Reveal this Text or Code Snippet]]

Key Benefits of This Approach

Compile-Time Safety: By using CreateLogger<T>(), we ensure type safety and eliminate potential compile-time errors.

Testability: This approach makes your code more testable, as the logger can be correctly injected into static methods without creating tight coupling.

Clarity: It provides clarity within your test cases, making it evident that you're utilizing a logger specific to your testing context.

Conclusion

Passing ILogger to static classes in C# can be tricky, but by leveraging NullLoggerFactory, you can maintain both clarity and testability in your code. This simple adjustment allows your methods to have the logging functionality they require while staying robust and easy to test.

Embrace these practices to enhance your code quality and streamline your unit testing process. Happy coding!

Комментарии

Информация по комментариям в разработке

Похожие видео

  • О нас
  • Контакты
  • Отказ от ответственности - Disclaimer
  • Условия использования сайта - TOS
  • Политика конфиденциальности

video2dn Copyright © 2023 - 2025

Контакты для правообладателей [email protected]