Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Let's continue with the same lock interface and MutexLock implementation as yesterday. In order to switch from dependency injection using generics to a classical constructor injection we have to change the important object to something like this:
1: public class ImportantObject
2: {
3: private readonly Lock _lock;
4:
5: public ImportantObject() : this(new MutexLock())
6: {
7:
8: }
9:
10: public ImportantObject(Lock aLock)
11: {
12: _lock = aLock;
13: }
14:
15: public void ImportantMethod()
16: {
17: _lock.Lock();
18: // Do things.
19: _lock.Unlock();
20: }
21: }
Which can be tested like this:
1: public class Given_an_ImportantObject
2: {
3: class FakeLock : Lock
4: {
5: public int NumberOfLocks { get; private set; }
6:
7: public FakeLock()
8: {
9: NumberOfLocks = 0;
10: }
11:
12: public void Lock()
13: {
14: ++NumberOfLocks;
15: }
16:
17: public void Unlock()
18: {
19:
20: }
21: }
22:
23: private ImportantObject _importantObject;
24: private FakeLock _lock;
25:
26: public Given_an_ImportantObject()
27: {
28: _lock = new FakeLock();
29: _importantObject = new ImportantObject(_lock);
30: }
31:
32: [Fact]
33: void It_should_take_lock_when_ImportantMethod_is_called()
34: {
35: _importantObject.ImportantMethod();
36: Assert.Equal(1, _lock.NumberOfLocks);
37: }
38: }
However there is still one big problem with this solution. I'll tell you tomorrow.