Skip to content

Instantly share code, notes, and snippets.

@gamlerhart
Created November 8, 2010 20:49
Show Gist options
  • Save gamlerhart/668230 to your computer and use it in GitHub Desktop.
Save gamlerhart/668230 to your computer and use it in GitHub Desktop.
Unit Testing, Part II, Synchronisation Issues
public class ComplexBusinessOperations
{
private int moneyEarnedSoFar;
public int MoneyEarnedSoFar
{
get { return moneyEarnedSoFar; }
}
public void EarnMoney(int investment)
{
EarnMoneySubTaks(investment);
EarnMoneySubTaks(investment);
}
private void EarnMoneySubTaks(int investment)
{
for (int i = 0; i < investment; i++)
{
var result = EarnOneDollar();
moneyEarnedSoFar += result;
}
}
private int EarnOneDollar()
{
// This operation takes a while
Thread.Sleep(50);
return 1;
}
}
public class ComplexBusinessOperations
{
private int moneyEarnedSoFar;
public int MoneyEarnedSoFar
{
get { return moneyEarnedSoFar; }
}
public async Task EarnMoney(int investment)
{
var firstMoneyEarner = EarnMoneySubTaks(investment);
var secondMoneyEarner = EarnMoneySubTaks(investment);
await TaskEx.WhenAll(firstMoneyEarner, secondMoneyEarner);
}
private async Task EarnMoneySubTaks(int investment)
{
for (int i = 0; i < investment; i++)
{
var result = await EarnOneDollar();
moneyEarnedSoFar += result;
}
}
private Task<int> EarnOneDollar()
{
return TaskEx.Run(
() =>
{
// This operation takes a while
Thread.Sleep(50);
return 1;
});
}
}
[Test]
public void EarnMoney()
{
var toTest = new ComplexBusinessOperations();
toTest.EarnMoney(200);
Assert.AreEqual(400, toTest.MoneyEarnedSoFar);
}
[Test]
public void EarnMoney()
{
var toTest = new ComplexBusinessOperations();
var task = toTest.EarnMoney(200);
task.Wait();
Assert.AreEqual(400, toTest.MoneyEarnedSoFar);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment