HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

How can I better the readability of inline test data?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
canthereadabilitybettertesthowinlinedata

Problem

[TestCase(new[] { 1, 2 }, 1, Result = 2)]
[TestCase(new[] { 1, 2 }, 2, Result = 1)]
[TestCase(new[] { 1, 2, 3 }, 2, Result = 2)]
[TestCase(new[] { 1, 2, 3, 4 }, 2, Result = 2)]
[TestCase(new[] { 1, 2, 3, 4 }, 10, Result = 1)]
public int TotalPageCountIsAccurate(int[] testSequence, int pageSize)
{
    var pagedList = new PagedList(testSequence, 0, pageSize);
    return pagedList.TotalPageCount;
}


I wrote this test about five minutes ago and I can barely understand it - I dread to think how hard it will be to read in a few weeks. How can I refactor the TestCase attribute to improve readability?

I thought about using named arguments or (maybe) introducing a some well-named fields, but neither of these ideas appear to be feasible.

Solution

If I'm right you could do at least two things:

-
Generate the array and pass only the number of items to the test method.

-
Rename testSequence to something more descriptive, like items, elements etc.

[TestCase(2, 1, Result = 2)]
[TestCase(2, 2, Result = 1)]
[TestCase(3, 2, Result = 2)]
[TestCase(4, 2, Result = 2)]
[TestCase(4, 10, Result = 1)]
public int TotalPageCountIsAccurate(int itemCount, int pageSize)
{
    // generates the item array with itemCount items
    var items = Enumerable.Range(0, itemCount).ToArray();

    var pagedList = new PagedList(items, 0, pageSize);
    return pagedList.TotalPageCount;
}


(I can't check whether is it valid C# or not but I hope you get the idea.)

I would also create a test with an empty array.

Code Snippets

[TestCase(2, 1, Result = 2)]
[TestCase(2, 2, Result = 1)]
[TestCase(3, 2, Result = 2)]
[TestCase(4, 2, Result = 2)]
[TestCase(4, 10, Result = 1)]
public int TotalPageCountIsAccurate(int itemCount, int pageSize)
{
    // generates the item array with itemCount items
    var items = Enumerable.Range(0, itemCount).ToArray();

    var pagedList = new PagedList<int>(items, 0, pageSize);
    return pagedList.TotalPageCount;
}

Context

StackExchange Code Review Q#56080, answer score: 5

Revisions (0)

No revisions yet.