I am totally brand new to Unit Testing and am trying to learn off my own back. I have failed at the first hurdle and despite countless books and web sites I cannot see what I am doing wrong... Please can someone tell me?? I have an Action ViewResult as follows I am looking to test:
public ViewResult ProductList()
{
List<ProductItem> allProducts = CallGetAllProducts();
return View(allProducts);
}
You can see it is calling a function:
private List<ProductItem> CallGetAllProducts()
{
var productFilePath = Server.MapPath(@"~/CSV/products.csv");
var products = new ProductsCSV();
return (products.GetAllProductsFromCSV(productFilePath));
}
Which is in turn calling the following function:
public List<ProductItem> GetAllProductsFromCSV(string csvPath)
{
String[] csvData = File.ReadAllLines(csvPath);
List<ProductItem> result = new List<ProductItem>();
foreach (string csvrow in csvData)
{
var fields = csvrow.Split(',');
ProductItem prod = new ProductItem()
{
ID = Convert.ToInt32(fields[0]),
Description = fields[1],
Item = fields[2][0],
Price = Convert.ToDecimal(fields[3]),
ImagePath = fields[4],
Barcode = fields[5]
};
result.Add(prod);
}
return result;
}
I have a Unit Test project I have created with the following test method in the appropriate ControllerTest file:
[TestMethod()]
public void ProductListGetsViewResult()
{
ProductsController controller = new ProductsController();
ViewResult result = controller.ProductList() as ViewResult;
Assert.IsNotNull(result);
}
I have all the correct references setup as far as I can see, however the results of running this test are coming back with:
Result Message:
Test method ShoppingBasket.Controllers.Tests.ProductsControllerTests.ProductListGetsViewResult threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
It looks like the problem is with the calling of the ViewResult in the 'Act' part of the process... But Why, I dont know.