Skip to content

Instantly share code, notes, and snippets.

@programatt
Created February 17, 2012 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save programatt/1850648 to your computer and use it in GitHub Desktop.
Save programatt/1850648 to your computer and use it in GitHub Desktop.
Instrument with property access
public class Instrument : DynamicObject
{
public int FinancialInstrumentId { get; private set; }
public string SpecialType { get; private set; }
public Instrument(int finId,string specialType)
{
FinancialInstrumentId = finId;
SpecialType = specialType;
}
public bool Is(string specialType)
{
return SpecialType.Contains(specialType);
}
public override bool TryGetMember(GetMemberBinder binder,
out object result)
{
if (!binder.Name.StartsWith("Is")) throw new ArgumentException("Property doesn't exist");
result = SpecialType.Contains(binder.Name.Substring(2));
return true;
}
}
[TestFixture]
public class InstrumentTests
{
[Test]
public void TestIsMethodWithCorrectSpecialType()
{
dynamic i = new Instrument(1,"FXBarrier");
var result = i.Is("FXBarrier");
Assert.IsTrue(result);
}
[Test]
public void TestIsMethodWithLongCorrectSpecialType()
{
dynamic i = new Instrument(3, "100FXBarrierOptionNoKO");
var result = i.Is("FXBarrier");
Assert.IsTrue(result);
}
[Test]
public void TestIsMethodWithIncorrectSpecialType()
{
dynamic i = new Instrument(5, "EuroOption");
var result = i.Is("FXBarrier");
Assert.IsFalse(result);
}
[Test]
public void TestIsWithMethodMissingOverrideWithCorrectSpecialType()
{
dynamic i = new Instrument(2, "FXBarrier");
var result = i.IsFXBarrier;
Assert.IsTrue(result);
}
[Test]
public void TestIsWithPropertyAccessLongCorrectSpecialType()
{
dynamic i = new Instrument(3, "100FXBarrierOptionNoKO");
var result = i.IsFXBarrier;
Assert.IsTrue(result);
}
[Test]
public void TestIsWithPropertyAccessIncorrectSpecialType()
{
dynamic i = new Instrument(6, "EuroOption");
var result = i.IsFXBarrier;
Assert.False(result);
}
[Test]
public void TestThrowsExceptionWhenPropertyNotStartingWithIs()
{
dynamic i = new Instrument(6, "EuroOption");
Assert.That(()=>i.EuroOption,Throws.ArgumentException);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment