2009 Advent Calendar December 12th
So now we need to fix the broken ImportantProvider making sure it uses one lock:
1: public class Given_two_transactions_from_the_same_ImportantProvider
2: {
3: private FakeLock _lock;
4: private ImportantProvider _importantProvider;
5: private Transaction _transaction1;
6: private Transaction _transaction2;
7:
8: public Given_two_transactions_from_the_same_ImportantProvider()
9: {
10: _lock = new FakeLock();
11: _importantProvider = new ImportantProvider(new DummyObject(), _lock);
12: _transaction1 = _importantProvider.Transaction;
13: _transaction2 = _importantProvider.Transaction;
14: }
15:
16: [Fact]
17: void It_should_be_two_different_transactions()
18: {
19: Assert.NotSame(_transaction1, _transaction2);
20: }
21:
22: [Fact]
23: void It_should_be_the_same_ImportantObject_returned_by_both_transactions()
24: {
25: Assert.Same(_transaction1.ImportantObject, _transaction2.ImportantObject);
26: }
27:
28: [Fact]
29: void It_should_take_lock_once_for_each_transaction()
30: {
31: Assert.Equal(2, _lock.NumberOfLocks);
32: }
33: }
As you can see in the test I've chosen constructor injection for the lock in this case:
1: public class ImportantProvider
2: {
3: private ImportantInterface _importantObject;
4: private Lock _lock;
5:
6: public ImportantProvider(ImportantInterface importantObject, Lock aLock)
7: {
8: _lock = aLock;
9: _importantObject = importantObject;
10: }
11:
12: public Transaction Transaction
13: {
14: get
15: {
16: return new Transaction(_importantObject, _lock);
17: }
18: }
19: }