I have two applications that are currently using a logging service that has been duplicated across both code bases. I am in the process of creating a small library that contains only the logging functionality so I can easily publish it as a NuGet package and use the shared logging library across both projects without duplicating my code.
My problem is the following: I have no idea how, or whether I should, test the basic functionality of the logger I have implemented.
My instinct was to start by unit testing the constructors, but because so much of the logic of configuring an instance of Log4NetLogger
is actually part of log4net, I felt as though I was unit testing their code rather than my own. As for the Write
functions, is it really necessary that I test if Log4Net actually writes to a file or console? It feels like I will end up testing an infinite number of use cases related to potential log4net configurations.
public interface ILogger
{
void Write(LogLevel level, string message);
void Write(LogLevel level, string message, object obj);
}
public class Log4NetLogger : ILogger
{
private ILog Logger { get; }
private readonly string InitializationMessage = "Initializing logger...";
public Log4NetLogger()
{
BasicConfigurator.Configure();
Logger = LogManager.GetLogger(typeof(Log4NetLogger));
Write(LogLevel.Debug, InitializationMessage);
}
public Log4NetLogger(string configurationFile)
{
XmlConfigurator.Configure(LogManager.GetRepository(Assembly.GetCallingAssembly()), new FileInfo(configurationFile));
Logger = LogManager.GetLogger(typeof(Log4NetLogger));
Write(LogLevel.Debug, InitializationMessage);
}
public void Write(LogLevel level, string message, object obj)
{
var serialized = JsonConvert.SerializeObject(obj);
Write(level, $"message: {message} object:{serialized}");
}
public void Write(LogLevel level, string message)
{
switch (level)
{
case LogLevel.Debug: Logger.Debug(message); break;
case LogLevel.Information: Logger.Info(message); break;
case LogLevel.Warning: Logger.Warn(message); break;
case LogLevel.Error: Logger.Error(message); break;
case LogLevel.Fatal: Logger.Fatal(message); break;
}
}
}
The point of the ILogger
interface is to enable me to do Dependency Injection, so I can inject mocks into consumers of the service, enabling me to test them without having the need for a dependency on log4net.
If anyone can tell me if this is actually testable and how you might approach testing this yourself if it is indeed worth testing. Any guidance or resources relating to this would be hugely appreciated.
Aucun commentaire:
Enregistrer un commentaire