A unit test run against a simple class using EntityFramework never completes, here's the code:
public class DbContext1 : DbContext
{
public DbContext1(string connectionString)
{
}
}
public class Program
{
private static readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1);
public async Task Run()
{
await _lock.WaitAsync();
try
{
await InsertDbRow();
}
finally
{
_lock.Release();
}
}
private static async Task InsertDbRow()
{
await RetryWrapperAsync(async () =>
{
using DbContext1 dbContext = new DbContext1("con str");
await dbContext.SaveChangesAsync();
});
}
public static async Task RetryWrapperAsync(Func<Task> operation)
{
for (int i = 0; i < 3; i++)
{
try
{
await operation();
break;
}
catch (Exception)
{
await Task.Delay(100);
}
};
}
}
[TestClass]
public class ProgramTest
{
private readonly DbContext1 mockContext1 = Mock.Create<DbContext1>();
[TestInitialize]
public void SetUp()
{
Mock.Arrange(() => new DbContext1("con str")).Returns(mockContext1);
}
[TestMethod]
public async Task TestMethod()
{
// Arrange
Program program = new Program();
// Act
await program.Run(); // <-- at this point the test hangs
}
}
Adding do-nothing arrangement on mockContext.SaveChanges fixes the hang, but the expectation is that mock will handle this case by default and there is no need to be explicitly arranged.