Calculatornamespace UnitTestApp{ public class Calculator { public int Add(int a, int b) { return a + b; } private static readonly object objSync = new object(); private static Calculator instance = null; public static Calculator GetInstance() { if (instance == null) { lock (objSync) { if (instance == null) { instance = new Calculator(); } } } return instance; } }}
5、新增NUnitTest类进行单元测试
UnitTestusing NUnit.Framework;namespace UnitTestApp{ [TestFixture] public class NUnitTest { [Test] public void AddTest() { var calc = new Calculator(); var result = calc.Add(1, 1); Assert.AreEqual(2, result); } [Test] public void AddTestFailure() { var calc = new Calculator(); var result = calc.Add(1, 1); Assert.AreEqual(10, result); } [Test] public void SingtonTest1() { var calc = Calculator.GetInstance(); Assert.IsNull(calc); } [Test] public void SingtonTest2() { var calc1 = Calculator.GetInstance(); var calc2 = Calculator.GetInstance(); Assert.IsTrue(object.Equals(calc1, calc2)); } }}