namespace NUnit.Specification { public abstract class SpecificationBase { [TestFixtureSetUp] public void SetUp() { Setup(); Given(); When(); } public virtual void Setup() { } private void Given() { IEnumerable<MethodInfo> publicMethods = this.GetType().GetMethods(); publicMethods.Where(m => m.GetCustomAttributes(typeof(GivenAttribute), false).Count() != 0) .ToList() .ForEach(m => m.Invoke(this, new object[0])); publicMethods.Where(m => m.GetCustomAttributes(typeof(AndAttribute), false).Count() != 0) .ToList() .ForEach(m => m.Invoke(this, new object[0])); } private void When() { this.GetType() .GetMethods() .Where(m => m.GetCustomAttributes(typeof(WhenAttribute), false).Count() != 0) .ToList() .ForEach(m => m.Invoke(this, new object[0])); } [TestFixtureTearDown] public void TearDown() { Teardown(); } public virtual void Teardown() { } } public class SpecificationAttribute : TestFixtureAttribute { } public class GivenAttribute : Attribute { } public class AndAttribute : Attribute { } public class WhenAttribute : Attribute { } public class ThenAttribute : TestAttribute { } }
[Specification] public class Create_invoice_for_regular_customer : SpecificationBase { private Customer _customer; private List<Transaction> _transactions; private Document _invoice; public override void Setup() { // General context setup like DateTimeProvider.Current = new Mock<DateTimeProvider>().Object; Mock.Get(DateTimeProvider.Current).Setup(m => m.GetCurrentTime()).Returns(new DateTime(2012, 10, 26)); } [Given] public void Customer_is_regular_company() { _customer= new Customer () { Name = "Jedi" }; } [And] public void Set_of_transactions_representing_monthly_usage() { _transactions = new[] { new Transaction() { Amount = 25 }, new Transaction() { Amount = 16 }, new Transaction() { Amount = 32 }, }.ToList(); } [When] public void Creating_monthly_usage_document() { _invoice = DocumentCreator.CreateMonthlyPaymentInvoice(_customer, _transactions); } [Then] public void Document_should_contain_transactions_and_not_contain_bank_fee() { var expectedInvoice = new ExpectedInvoice(); Assert.That(_invoice, Is.EqualTo(expectedInvoice)); } public override void Teardown() { DateTimeProvider.Current = new DateTimeProvider(); } }
Source: https://habr.com/ru/post/156325/
All Articles