Reputation: 4800
I'm writing unit tests for a C# project using Visual Studio's built-in unit testing tools, and many of these tests require the use of a file TestData.xlsx
.
Currently when I run my tests I'm noticing that the previous test is not releasing its hold on the file in time for the next test to use it. This causes the test to fail. How am I supposed to write my tests in order to prevent this from happening?
Here is an example of what I'm dealing with:
[TestClass]
public class ExcelWorksheetExtensionTests
{
private ExcelPackage excelPackage;
private ExcelWorksheet excelWorksheet;
[TestInitialize]
[DeploymentItem(@"Assets\TestData.xlsx")]
public void TestInitialize()
{
FileInfo fileInfo = new FileInfo(@"Assets\TestData.xlsx");
this.excelPackage = new ExcelPackage(fileInfo);
this.excelWorksheet = this.excelPackage.Workbook.Worksheets["Sheet1"];
}
[TestCleanup]
public void TestCleanup()
{
this.excelPackage.Dispose();
}
// This test may succeed...
[TestMethod]
public void TestGetRowIndexForExistingName()
{
Assert.AreEqual(this.excelWorksheet.GetRowIndex("Object49").Value, 6);
}
// ...But this test will fail because TestInitialize re-runs too quickly.
[TestMethod]
public void TestGetRowIndexForMissingName()
{
Assert.IsFalse(this.excelWorksheet.GetRowIndex("NonExistentName").HasValue);
}
}
Upvotes: 3
Views: 752
Reputation: 1541
I'm not too familiar with the EPPlus but what from what I can see is that you have a shared resource ExcelWorksheet
and it's begin accessed from different threads in each test. You have to check to see if the querying calls are thread-safe?
I'm not sure what version of 'EPPlus' you are using but with the latest version (4.1.1) there isn't a function called GetRowIndex
but nevertheless I have improved the test to look like the following:
[TestClass]
public class ExcelWorksheetExtensionTests
{
private FileInfo _fileInfo;
[TestInitialize]
public void TestInitialize()
{
_fileInfo = new FileInfo(@"C:\Test.xlsx");
}
// This test may succeed...
[TestMethod]
public void TestGetRowIndexForExistingName()
{
using (var excelPackage = new ExcelPackage(_fileInfo))
{
var excelWorksheet = excelPackage.Workbook.Worksheets["Sheet1"];
Assert.AreEqual(excelWorksheet.GetValue(1, 1), 6.0);
}
}
// ...But this test will fail because TestInitialize re-runs too quickly.
[TestMethod]
public void TestGetRowIndexForMissingName()
{
using (var excelPackage = new ExcelPackage(_fileInfo))
{
var excelWorksheet = excelPackage.Workbook.Worksheets["Sheet1"];
Assert.IsFalse(excelWorksheet.GetValue(1, 1) == null);
}
}
}
Now each test has it's now instance of ExcelWorksheet
and the potential race conditions on the previous shared resource are eliminated with both tests now passing with flying colors.
Upvotes: 2