Search code examples
c#.netxunitautofixture

How to test in xUnit, UTC Date in millisecond for API method


I am working on xUnit test for Web API project. One of the method takes UTC Date in millisecond, how can I test which confirms the input parameter to API method is valid millisecond. I have logic to convert millisecond to date

public static DateTimeOffset DateTimeCalculation(long milSec)
{
        DateTimeOffset epochTime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
        return epochTime.AddMilliseconds(milSec);
}

test method

   [Fact]
    public async Task GetPersonMethod_MustTake_DateParameter_InMilliSecond()
    {
        //Arrange
        var fixture = new Fixture();
        long startDateTimeUtc = 1626994800000;


        DateTimeOffset starTimeOffset = DateTimeCalculationHelper.DateTimeCalculation(startDateTimeUtc);

        //Act



        //Assert
    }

Solution

  • When writing unit tests, you should have a clear understanding about actual result and expected result. Your test should look like below.

    Alway's ask yourself, Given some input what's the expected output?

    public void GetPersonMethod_MustTake_DateParameter_InMilliSecond()
        {
            //Arrange
            long startDateTimeUtc = 1626994800000;
    
            //Act
            DateTimeOffset starTimeOffset = DateTimeCalculationHelper.DateTimeCalculation(startDateTimeUtc);
    
            //Assert
            string actual = starTimeOffset.ToString();
            string expected = "22/07/2021 11:00:00 PM +00:00";
            Assert.Equal(expected, actual);
        }