Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private bool _initCalled = false;
- private void Initialize()
- {
- if (!_initCalled)
- {
- lock (this)
- {
- if (_initCalled)
- return;
- NoConfigInit();
- _initCalled = true;
- }
- }
- }
- public class Class3
- {
- private bool _initCalled = false;
- public void Initialize()
- {
- if (!_initCalled)
- {
- lock (this)
- {
- // we need to insert an empty DummyMethod here
- DummyMethod();
- if (_initCalled)
- return;
- NoConfigInit();
- _initCalled = true;
- }
- }
- }
- private void DummyMethod()
- {
- // This method stays empty in production code.
- // It provides the hook for the unit test.
- }
- private void NoConfigInit()
- {
- }
- }
- [TestMethod]
- public void TestMethod1()
- {
- using (ShimsContext.Create())
- {
- // This is the value to capture whether the NoConfigInit was called
- var initCalled = false;
- // Here the DummyMethod comes into play
- Namespace.Fakes.ShimClass3.AllInstances.DummyMethod =
- class3 =>
- typeof(Class3).GetField("_initCalled", BindingFlags.Instance | BindingFlags.NonPublic)
- .SetValue(class3, true);
- // This is just a hook to check whether the NoConfigInit is called.
- // You may be able to test this using some other ways (e.g. asserting on state etc.)
- Namespace.Fakes.ShimClass3.AllInstances.NoConfigInit = class3 => initCalled = true;
- // act
- new Class3().Initialize();
- // assert
- Assert.IsFalse(initCalled);
- }
- }
- int calls = 0;
- Namespace.Fakes.ShimClass3.AllInstances.InitCalledGet = class3 => calls++ > 0;
- using System.Threading.Tasks;
- using FakeItEasy;
- using Xunit;
- namespace Rovio.Beacon.Cloud.Client.Tests
- {
- public class MyClass
- {
- private readonly object _lock = new object();
- private readonly IMyInterface _noConfig;
- private bool _initCalled;
- public MyClass(IMyInterface noConfig)
- {
- _noConfig = noConfig;
- }
- public void Initialize()
- {
- if (_initCalled)
- {
- return;
- }
- lock (_lock)
- {
- if (_initCalled)
- {
- return;
- }
- _noConfig.Init();
- _initCalled = true;
- }
- }
- }
- public interface IMyInterface
- {
- void Init();
- }
- public class MyTests
- {
- private readonly IMyInterface _myInterface;
- private readonly MyClass _myClass;
- public MyTests()
- {
- _myInterface = A.Fake<IMyInterface>();
- _myClass = new MyClass(_myInterface);
- }
- [Fact]
- public async void Initialize_CallInitializeConcurrently_InitNoConfigOnlyCalledOnce()
- {
- Task[] tasks =
- {
- Task.Run(() => _myClass.Initialize()),
- Task.Run(() => _myClass.Initialize())
- };
- await Task.WhenAll(tasks);
- A.CallTo(() => _myInterface.Init()).MustHaveHappenedOnceExactly();
- }
- [Fact]
- public void Initialize_CallInitializeConsecutively_InitNoConfigOnlyCalledOnce()
- {
- _myClass.Initialize();
- _myClass.Initialize();
- A.CallTo(() => _myInterface.Init()).MustHaveHappenedOnceExactly();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement