I need to test a function which uses CSVHelper
{
private readonly CsvConfiguration _csvConfig;
public CsvWriterService(CsvConfiguration csvConfig)
{
_csvConfig = csvConfig;
}
public void WriteCsv(TradeRecord record, string filePath)
{
using var writer = new StreamWriter(filePath);
using var csv = new CsvWriter(writer, _csvConfig);
csv.Context.RegisterClassMap<TradeRecordMap>();
csv.WriteHeader<TradeRecord>();
csv.WriteRecord(record);
}
}
How can I mock the _csvConfig in the constructor? What I have so far:
private readonly CsvConfiguration _csvConfig;
public CsvWriterServiceTest()
{
CsvWriterService_Sut = new CsvWriterService(_csvConfig);
}
[Fact]
public void WriteCsv_RecordsAndFilePath_Should_WriteCsv()
{
//Arrange
var date = new DateTime(2021, 1, 1);
var records = new List<TradeRecord>{};
var filePath = "TestFilePath.csv";
//Act
CsvWriterService_Sut.WriteCsv(records, filePath);
//Assert
Assert.True(File.Exists(filePath));
}
CsvWriterService_Sut is not instantiated and gives a NullReferenceException .
Thank you all
Mocking configuration can be a pain and I've found that it's generally not worth mocking it. Personally, I would just create a new instance of CsvConfiguration and pass that into your constructor.
Not everything needs to be mocked in testing. Sometimes you can just use a regular instance of the class.