Creating List of Test Data for a Class (C#)

Sometimes when you are developing an application you need to have a set of test data to run the system but you may not have the database in place, or you need the data to be the same each time you run the test. Here’s an example how to do this.

In this example we are writing a class for Invoices, suitably called Invoice. Somewhere we want to have a list of invoices displayed on a page and the source for this will be a List<Invoice> and we obtain that by calling a function GetInvoices().

To set up the list of invoices all we need to do is use the new operator as shown in the example code below.

In passing here, it is a better technique to use IEnumerable instead of List<T> as a return type as it gives a bit more flexibility for future code changes.

public class Invoice
{
  // define the class properties
  public int InvoiceID { get; set; }
  public int Gross { get; set; }

  // return test data
  IEnumerable GetInvoices()
  {
    // test data
    return new List() {
      new Invoice(){InvoiceID=1, Gross=100},
      new Invoice(){InvoiceID=2, Gross=120},
      new Invoice(){InvoiceID=3, Gross=330}
    };
  }
}