Skip to content

Instantly share code, notes, and snippets.

@jovaneyck
Last active May 25, 2018 13:01
Show Gist options
  • Save jovaneyck/444fd6c39933ce9b5984f06d9193179a to your computer and use it in GitHub Desktop.
Save jovaneyck/444fd6c39933ce9b5984f06d9193179a to your computer and use it in GitHub Desktop.
GivenWhenThen hierarchy abuse example. Try to investigate failure of WhenTargetContractDoesNotCorrespondToSourceContractOtherFirmnessLevel.ThenRuleShouldFail()
[TestClass]
public class WhenTargetContractDoesNotCorrespondToSourceContractOtherFirmnessLevel : GivenRulesDeterminedFromDatabaseConfiguredRules
{
private ICapacityConversionRequest capacityConversionRequest;
private IRepository<ITransmissionService> transmissionServiceRepository;
private void GivenParameters()
{
this.capacityConversionRequest = MockRepository.GenerateStub<ICapacityConversionRequest>();
var requestLine = MockRepository.GenerateStub<ICapacityConversionRequestLine>();
var sourceContract = MockRepository.GenerateStub<ITransportationContract>();
var sourceTs = MockRepository.GenerateStub<ITransmissionService>();
var sourceTsDetail = MockRepository.GenerateStub<ITransmissionServiceDetail>();
var target = MockRepository.GenerateStub<ICapacityConversionTarget>();
var targetContract = MockRepository.GenerateStub<ITransportationContract>();
var targetTs = MockRepository.GenerateStub<ITransmissionService>();
var targetTsDetail = MockRepository.GenerateStub<ITransmissionServiceDetail>();
sourceTs.Id = 1001;
sourceTsDetail.FirmnessLevel = MockRepository.GenerateStub<IFirmnessLevel>();
sourceTsDetail.FirmnessLevel.Id = 2001;
sourceTsDetail.GasTransportRouteDirection = GasTransportRouteDirection.PositiveDirection;
sourceTsDetail.GasTransportRouteId = 3001;
targetTs.Id = 1002;
targetTsDetail.FirmnessLevel = MockRepository.GenerateStub<IFirmnessLevel>();
targetTsDetail.FirmnessLevel.Id = 2999;
targetTsDetail.GasTransportRouteDirection = GasTransportRouteDirection.PositiveDirection;
targetTsDetail.GasTransportRouteId = 3001;
sourceTs.Stub(p => p.Details).Return(new[] { sourceTsDetail });
sourceContract.Stub(p => p.FirstBookedTransmissionServiceId).Return(sourceTs.Id);
requestLine.Stub(p => p.TransportationContract).Return(sourceContract);
this.capacityConversionRequest.Stub(p => p.CapacityConversionRequestLines).Return(new[] { requestLine });
targetTs.Stub(p => p.Details).Return(new[] { targetTsDetail });
targetContract.Stub(p => p.FirstBookedTransmissionServiceId).Return(targetTs.Id);
target.Stub(p => p.TransportationContract).Return(targetContract);
this.capacityConversionRequest.Stub(p => p.CapacityConversionTargets).Return(new[] { target });
this.transmissionServiceRepository = MockRepository.GenerateStub<IRepository<ITransmissionService>>();
this.Mock(this.transmissionServiceRepository, new[] { sourceTs, targetTs });
}
/// <summary>
/// Test setup
/// </summary>
protected override void Given()
{
base.Given();
this.GivenParameters();
this.RuleValidator = new CapacityConversionRequestTargetCorrespondsSourceRuleValidator(this.capacityConversionRequest, this.transmissionServiceRepository);
this.RuleToValidate = GetRuleToValidate(RuleCode.CapacityConversionRequestTargetCorrespondsSourceFirmnessLevelBusinessRule);
this.RuleValidationContext = new RuleValidationContext(this.RuleToValidate);
}
[TestMethod]
public void ThenRuleShouldFail()
{
Assert.IsFalse(this.RuleValidationContext.ValidationResult.Succeeded);
}
}
/// <summary>
/// Generated base class for rulevalidator tests, containing rules corresponding to configured rules from the database.
/// It is not the idea to have them retrieved from the database at runtime, since this would slow down the tests.
/// This class needs to be generated once in a while
/// </summary>
public class GivenRulesDeterminedFromDatabaseConfiguredRules : GivenWhenThen
{
/// <summary>
/// Gets a value indicating whether to validate the rule in the 'When' method.
/// </summary>
/// <value><c>True</c> if the rule must be validated in the 'When' method; otherwise, <c>false</c>.</value>
protected bool ValidateRuleInWhen { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="GivenRulesDeterminedFromDatabaseConfiguredRules"/> class.
/// </summary>
public GivenRulesDeterminedFromDatabaseConfiguredRules()
: this(true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GivenRulesDeterminedFromDatabaseConfiguredRules"/> class.
/// </summary>
/// <param name="validateRuleInWhen">If set to <c>true</c> [validate rule in when].</param>
public GivenRulesDeterminedFromDatabaseConfiguredRules(
bool validateRuleInWhen)
{
this.ValidateRuleInWhen = validateRuleInWhen;
}
/// <summary>
/// Gets or sets the rule to validate.
/// </summary>
/// <value>The rule to validate.</value>
protected Rule RuleToValidate { get; set; }
/// <summary>
/// Gets or sets the rule validation context.
/// </summary>
/// <value>The rule validation context.</value>
protected RuleValidationContext RuleValidationContext { get; set; }
/// <summary>
/// Gets or sets the rule validator.
/// </summary>
/// <value>The rule validator</value>
protected RuleValidatorBase RuleValidator { get; set; }
/// <summary>
/// Gets the rule to validate.
/// </summary>
/// <param name="ruleToValidateCode">The rule to validate code.</param>
/// <returns>The corresponding rule</returns>
public static Rule GetRuleToValidate(string ruleToValidateCode)
{
return UnittestRules.GetRule(ruleToValidateCode);
}
/// <summary>
/// Does something in the system that will be asserted later on
/// </summary>
protected override void When()
{
base.When();
if (this.ValidateRuleInWhen)
{
this.RuleValidator.ValidateRule(this.RuleValidationContext);
}
}
}
/// <summary>
/// Base class for unittest classes that follow the Given-When-Then approach
/// </summary>
[TestClass]
public abstract class GivenWhenThen : IDisposable
{
#region Private Fields
private bool disposed;
private ContainerBuilder builder;
private UnitTestingCachingStrategy unitTestingCachingStrategy;
#endregion
#region Constructors
/// <summary>
/// Initializes the <see cref="GivenWhenThen"/> class.
/// </summary>
static GivenWhenThen()
{
Framework.Logging.Logger.Configure(new Log4NetLogger());
ICurrentTime mithraAgreedMockedTime = new UnitTestTime();
TimeFactory.Initialize(mithraAgreedMockedTime);
AdvicePolicy.DisableExecutionOfAdviceType<TransactionAdviceAttribute>();
AdvicePolicy.DisableExecutionOfAdviceType<NHibernateSessionAdviceAttribute>();
AdvicePolicy.DisableExecutionOfAdviceType<TracingAdviceAttribute>();
Framework.Logging.Logger.Debug("GivenWhenThen", "Starting unittests");
}
#endregion
/// <summary>
/// Registers a (dynamic) mock (will return null or 0 for unexpected calls).
/// </summary>
/// <typeparam name="T">Type of the mock</typeparam>
/// <returns>The created and registered mock.</returns>
protected T RegisterMock<T>() where T : class
{
T mock = MockRepository.GenerateMock<T>();
this.CurrentContainerBuilder
.RegisterInstance(mock)
.As<T>();
return mock;
}
/// <summary>
/// Resolves a registered instance.
/// </summary>
/// <typeparam name="T">The type of instance</typeparam>
/// <returns>The instance</returns>
protected T Resolve<T>() where T : class
{
return MithraDependency.Resolve<T>();
}
/// <summary>
/// Initializes a new instance of the <see cref="GivenWhenThen"/> class.
/// </summary>
protected GivenWhenThen()
{
AuthorizationHelper.SetWinFormsCredentials();
}
#region Destructor
/// <summary>
/// Finalizes an instance of the <see cref="GivenWhenThen"/> class.
/// </summary>
~GivenWhenThen()
{
this.Dispose(false);
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the current container builder.
/// </summary>
/// <value>
/// The current container builder.
/// </value>
protected ContainerBuilder CurrentContainerBuilder
{
get
{
if (this.builder == null)
{
this.builder = new ContainerBuilder();
}
return this.builder;
}
}
/// <summary>
/// Gets the unit testing caching strategy.
/// </summary>
/// <value>The unit testing caching strategy.</value>
protected UnitTestingCachingStrategy UnitTestingCachingStrategy
{
get
{
if (this.unitTestingCachingStrategy == null)
{
this.unitTestingCachingStrategy = new UnitTestingCachingStrategy();
}
return this.unitTestingCachingStrategy;
}
}
#endregion
#region Protected Methods
/// <summary>
/// Initializes the context in which the test should run
/// </summary>
protected virtual void Given()
{
}
/// <summary>
/// Does something in the system that will be asserted later on
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "When", Justification = "We are only using C# for our tests, so this is not an issue.")]
protected virtual void When()
{
}
/// <summary>
/// Called when the test has ended and cleaning actions can be executed.
/// </summary>
protected virtual void OnTestCleanup()
{
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing">Returns <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
}
}
this.disposed = true;
}
#endregion
#region Public Methods
/// <summary>
/// Code that is executed before each test, like registering dependencies,
/// set-up of the test context.
/// </summary>
[TestInitialize]
public virtual void BeforeEachTest()
{
ICurrentTime mithraAgreedMockedTime = new UnitTestTime();
TimeFactory.Initialize(mithraAgreedMockedTime);
this.Given();
IContainer container = this.CurrentContainerBuilder.Build();
MithraDependency.SetAutofacContainer(container);
this.When();
}
/// <summary>
/// Code that is performed after each test.
/// </summary>
[TestCleanup]
public void AfterEachTest()
{
this.OnTestCleanup();
this.Dispose(true);
MithraDependency.SetAutofacContainer(null);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Utility Methods
protected void LogDebug(string message)
{
Debug.WriteLine(message);
Logger.Debug(this, message);
}
protected virtual void Mock<T>(IRepository<T> repository, IList<T> collection) where T : class, IIdentifyable
{
RepositoryMockBuilder.Mock(repository, collection);
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment