I have a Unit test function which worked. When I incorporated ILogger and Moq framework, its not catching exceptions anymore. See Last test below. In debugging the unit test step by step, I know the Exception is thrown. So not sure why its not displaying in Nunit and causing an error.
Error:
Message: Expected: <System.ArgumentException> But was: no exception thrown
using System;
using ElectronicsStore.Models;
using Microsoft.Extensions.Logging;
namespace ElectronicsStore.Service
{
public class ParseVendorSupply
{
private readonly ILogger _logger;
public ParseVendorSupply(ILogger logger)
{
_logger = logger;
}
public VendorSupply FromCsv(string csvLine)
{
VendorSupply vendorsupply = new VendorSupply();
try
{
string[] values = csvLine.Split(',');
if (values.Length > 3)
{
throw new System.ArgumentException("Too much data");
}
vendorsupply.VendorId = Convert.ToInt16(values[0]);
vendorsupply.ProductId = Convert.ToInt16(values[1]);
vendorsupply.Quantity = Convert.ToInt16(values[2]);
}
catch (Exception)
{
_logger.LogInformation("An exception was thrown attempting");
}
return vendorsupply;
}
}
}
NUnit Test:
public class ParseVendorSupplyNunit
{
ILogger logger;
// This Works
[Test]
public void FromCsv_ParseCorrectly()
{
var logger = new Mock<ILogger>();
var parseVendorSupply = new ParseVendorSupply(logger.Object);
string csvLineTest = "5,8,3";
VendorSupply vendorsupply = parseVendorSupply.FromCsv(csvLineTest);
Assert.AreEqual(5, vendorsupply.VendorId);
Assert.AreEqual(8, vendorsupply.ProductId);
Assert.AreEqual(3, vendorsupply.Quantity);
}
// This does not work anymore,after adding ILogger and Moq
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
var logger = new Mock<ILogger>();
var parseVendorSupply = new ParseVendorSupply(logger.Object);
string csvLineTest = "5,8,3,9,5";
Assert.That(() => parseVendorSupply.FromCsv(csvLineTest), Throws.ArgumentException);
}
Message: Expected: <System.ArgumentException> But was: no exception thrown