Search code examples
xunitdatarow

xunit test previousValue


I would like to evaluate a data series and output the respective previous value. For this I use the following code:

private int PrevInt(int CurrentInt)
    {
        PrevIntList.Add(CurrentInt);
        for (int i = 0; i < PrevIntList.Count; i++) { if (i >= 1) prevIntListValue = PrevIntList[i - 1]; }
        return prevIntListValue;
    }

To run a test with Xunit, I need a data series as source (e.g. 1,2,3,4,5) and the call to my method, which determines the respective predecessor value and confirms it as correct. How can I create such a test correctly.

Thanks a lot for the support!


Solution

  • Please see my comment about your for loop, you don't need it at all, you can compute the correct index of the previous element directly.

    The "arrange, act, assert" paradigm will work just fine for this case, except that the "act" part occurs during the arranging. You can make a Theory and provide the sequence of integers in an array. In the "arrange" part, you make a new instance of your class and set up the list by calling the method, in the act part you then test a specific value against the expected one.

    Assuming PrevIntList is a member of you class, it could look like this

        public class YourClass
        {
            private List<int> PrevIntList = new List<int>();
            public int PrevInt(int CurrentInt)
            {
                int prevIntListValue = -1;
                PrevIntList.Add(CurrentInt);
                for (int i = 0; i < PrevIntList.Count; i++) { if (i >= 1) prevIntListValue = PrevIntList[i - 1]; }
                return prevIntListValue;
            }
        }
    
        public class YourClassUnitTests
        {
            [Theory]
            [InlineData(new int[] { 1, 2, 3, 4, 5 })]
            public void PrevIntReturnsCorrectValue(int[] data)
            {
                // Sanity check-- the method only works when data has at least two elements
                Assert.True(data.Length >= 2, $"Bad test data, array must have at least 2 elements but only has {data.Length}.");
    
                // Arrange (and Act)
                YourClass instance = new YourClass();
                int actual = -1;
                for (int i = 0; i < data.Length; i++)
                {
                    actual = instance.PrevInt(data[i]);
                }
    
                // Act
                // During arranging the method under test was called and the result saved in 'actual'
    
                // Assert
                int expected = data[data.Length - 2];
                Assert.Equal(expected, actual);
            }
        }
    

    Don't forget to credit Stack Overflow for helping when you submit your homework assignment.