I have a class that checks if the current day of the week is Wednesday. It looks like this:
public class Wednesday
{
public string IsWednesday()
{
if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday)
{
return "It’s Wednesday";
}
else
{
return "It’s not Wednesday";
}
}
}
Don't worry about the return type, I know that it's bad in this particular example to return a magic string. We're focused on its purpose, not implementation.
I would love to cover it with unit tests for both cases of the current weekday being Wednesday and being anything but Wednesday.
I am new to unit testing and I'm wondering what the best solution would be in this example.
Right now, I'm using VS2019 with MS Test V2. I've tested both scenarios like this:
[TestClass]
public class WednesdayTests
{
[TestMethod]
public void IsWednesday_CurrentWeekDayIsWednesday_ReturnsItsWedndesday()
{
if (!(DateTime.Now.DayOfWeek == DayOfWeek.Wednesday))
{
return;
}
// Arrange
Wednesday wednesdayObj = new Wednesday();
// Act
string result = wednesdayObj.IsWednesday();
// Assert
Assert.AreEqual("It’s Wednesday", result);
}
[TestMethod]
public void IsWednesday_CurrentWeekDayIsNotWednesday_ReturnsItsNotWednesday()
{
if (!(DateTime.Now.DayOfWeek != DayOfWeek.Wednesday))
{
return;
}
Wednesday wednesdayObj = new Wednesday();
string result = wednesdayObj.IsWednesday();
Assert.AreEqual("It’s not Wednesday", result);
}
}
Is it considered OK to return out of a test method when some condition is not met, like in my case?
Or is there something inherently wrong with my solution?
Glad to hear any suggestions from experienced software developers!
P.S. Just noticed that the test will only be conducted if it's actually Wendesday :) Wow, that's for sure is not the solution!