Created
January 25, 2024 15:36
-
-
Save tkouba/2295988ee4388973f35414cf4b8abf69 to your computer and use it in GitHub Desktop.
xUnit tests for calc business days https://stackoverflow.com/a/1646396/1498252
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace TestGetBusinessDays | |
{ | |
public class UnitTestCalcBusinessDays | |
{ | |
int GetBusinessDays(DateTime startD, DateTime endD) | |
{ | |
double calcBusinessDays = | |
1 + ((endD - startD).TotalDays * 5 - | |
(startD.DayOfWeek - endD.DayOfWeek) * 2) / 7; | |
if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--; | |
if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--; | |
return Convert.ToInt32(calcBusinessDays); | |
} | |
int GetBusinessDays(DateOnly startD, DateOnly endD) | |
{ | |
double calcBusinessDays = | |
1 + ((endD.DayNumber - startD.DayNumber) * 5 - | |
(startD.DayOfWeek - endD.DayOfWeek) * 2) / 7; | |
if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--; | |
if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--; | |
return Convert.ToInt32(calcBusinessDays); | |
} | |
public static TheoryData<DateTime, DateTime, int> DateTimeTheory = new() | |
{ | |
{ new DateTime(2024,1,1), new DateTime(2024,1,1), 1 }, // same day (Monday - Monday) | |
{ new DateTime(2024,1,1), new DateTime(2024,1,8), 6 }, // Monday - Monday | |
{ new DateTime(2024,1,1), new DateTime(2024,1,7), 5 }, // Monday - Sunday | |
{ new DateTime(2024,1,5), new DateTime(2024,1,8), 2 }, // Friday - Monday | |
{ new DateTime(2024,1,8), new DateTime(2024,1,12), 5 }, // Monday - Friday | |
{ new DateTime(2024,2,26), new DateTime(2024,3,1), 5 }, // Monday - Friday (February has 29 days) | |
{ new DateTime(2024,1,7), new DateTime(2024,1,8), 1 }, // Sunday - Monday | |
{ new DateTime(2024,1,6), new DateTime(2024,1,8), 1 }, // Saturday - Monday | |
{ new DateTime(2024,1,26), new DateTime(2024,2,1), 5 }, // Friday - Thursday | |
{ new DateTime(2024,1,24), new DateTime(2024,1,30), 5 }, // Wednesday - Tuesday | |
{ new DateTime(2024,1,24), new DateTime(2024,1,31), 6 }, // Wednesday - Wednesday | |
}; | |
[Theory, MemberData(nameof(DateTimeTheory))] | |
public void TestDateTime(DateTime startD, DateTime endD, int expected) | |
{ | |
Assert.Equal(expected, GetBusinessDays(startD, endD)); | |
} | |
[Theory, MemberData(nameof(DateTimeTheory))] | |
public void TestDateOnly(DateTime startD, DateTime endD, int expected) | |
{ | |
Assert.Equal(expected, GetBusinessDays(DateOnly.FromDateTime(startD), DateOnly.FromDateTime(endD))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment