Reputation: 2220
I have an Entity Framework method which simply adds a Product
to the database. When I run my test method this all works as expected.
I then have an AddProductAsync
method:
Task<Product> AddProductAsync(Product pToAdd)
{
return Task<Product>.Factory.StartNew(() => AddProduct(pToAdd));
}
When I run the test using this method the test runs but nothing actually happens. The break point in my AddProduct
method is never hit and nothing is added to the database. There is no error, no warning.
What am I doing wrong? Or shall I just wait for EF6?
Thanks in advance
Original Method:
public static Product AddProduct(Product pToAdd)
{
using (var viralDatabase = new ViralWearContext())
{
if (viralDatabase.Products.Any(p => p.Name == pToAdd.Name || p.Description == pToAdd.Description))
{
var result = viralDatabase.Products.First(p => p.Name == pToAdd.Name || p.Description == pToAdd.Description);
//set 0 so client knows it already exists
result.ProductID = 0;
return result;
}
else
{
var result = viralDatabase.Products.Add(pToAdd);
viralDatabase.SaveChanges();
return result;
}
}
}
Method called by Unit Test:
public async void AddProductsAsyncTest()
{
Stopwatch timer = new Stopwatch();
Product testProduct = GenerateTestProduct();
Product testProductTwo = GenerateTestProduct();
Product testProductThree = GenerateTestProduct();
timer.Start();
Product_Datalayer.AddProduct(testProduct);
Product_Datalayer.AddProduct(testProductTwo);
Product_Datalayer.AddProduct(testProductThree);
var time1 = timer.ElapsedMilliseconds;
Console.WriteLine(timer.ElapsedMilliseconds.ToString());
timer.Reset();
Product testProductAsync = GenerateTestProduct();
Product testProductTwoAsync = GenerateTestProduct();
Product testProductThreeAsync = GenerateTestProduct();
timer.Start();
var result1 = Product_Datalayer.AddProductAsync(testProductAsync);
var result2 = Product_Datalayer.AddProductAsync(testProductTwoAsync);
var result3 = Product_Datalayer.AddProductAsync(testProductThreeAsync);
await Task.WhenAll(result1, result2, result3);
var time2 = timer.ElapsedMilliseconds;
Console.WriteLine(timer.ElapsedMilliseconds.ToString());
}
Upvotes: 1
Views: 520
Reputation: 456537
You need to make your unit tests async Task
, not async void
. Note that async
unit tests are only supported by VS2012.
If you're on VS2010, you can use the Async Unit Tests project described here. I still recommend you use async Task
, so they will translate easily to VS2012 (which is not supported by the Async Unit Tests project).
Upvotes: 3