This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
0
Need help with Nsubstitute unit testing
Post Body
I have this logger class i want to unit test but im a bit lost on how i do it: Specifically with how to assert if the streamwriter wrote the correct message? I appreciate any help.
public class Logger
{
private readonly StreamWriter _writer;
private readonly IDateTimeProvider _dateTimeProvider;
public Logger(string path) : this(path, new DateTimeProvider(), new
StreamWriterProvider()) { }
public Logger(string path, IDateTimeProvider dateTimeProvider, IStreamWriterProvider streamWriterProvider)
{
_dateTimeProvider = dateTimeProvider;
_writer = streamWriterProvider.CreateStreamWriter(path);
Log("Logger initialized");
}
public void Log(string str)
{
_writer.WriteLine($"[{_dateTimeProvider.Now:dd.MM.yy HH:mm:ss}] {str}");
}
}
--
public interface IStreamWriterProvider
{
StreamWriter CreateStreamWriter(string path);
}
public class StreamWriterProvider : IStreamWriterProvider
{
public StreamWriter CreateStreamWriter(string path)
{
return new StreamWriter(File.Open(path, FileMode.Append))
{
AutoFlush = true
};
}
}
--
[Test]
public void Log_PrefixesInputWithDateTime()
{
// Arrange
var dateTime = new DateTime(2022, 1, 1, 12, 0, 0);
var expectedLogMessage = $"[{dateTime:dd.MM.yy HH:mm:ss}] Test message";
var dateTimeProvider = Substitute.For<IDateTimeProvider>();
dateTimeProvider.Now.Returns(dateTime);
var memoryStream = new MemoryStream();
var streamWriterProvider = Substitute.For<IStreamWriterProvider>();
streamWriterProvider.CreateStreamWriter(Arg.Any<string> ()).ReturnsForAnyArgs(new StreamWriter(new MemoryStream()));
Logger logger = new Logger("testPath", dateTimeProvider, streamWriterProvider);
// Act
logger.Log("Test message");
//Assert
// ASSERT THAT LOG IS EUQAL TO EXPECTED LOG MESSAGE
// Ensure that StreamWriter was created with the expected path
streamWriterProvider.Received().CreateStreamWriter("testPath");
}
Author
Account Strength
100%
Account Age
6 years
Verified Email
Yes
Verified Flair
No
Total Karma
22,481
Link Karma
16,478
Comment Karma
5,889
Profile updated: 1 day ago
Posts updated: 3 days ago
Subreddit
Post Details
We try to extract some basic information from the post title. This is not
always successful or accurate, please use your best judgement and compare
these values to the post title and body for confirmation.
- Posted
- 11 months ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/dotnet/comm...