Attribute für die Konfiguration von Verhalten

by robert 26. August 2009 16:49

Weit jenseits von spektakulär oder elegant, aber denoch nützlich ist das Verwenden von Attributen für die Konfiguration von Verhalten. Hier ein Beispiel für die Konfiguration von Testfällen:

[TestFixture] 
[RestartIocContainer(true)] [TruncateAllTables(true)]
public class CatalogDuplicationTest : TestBase
{
    [Test]
    public void SomeTest()
    {
        //
    }
}

Der Testfall kümmert sich beim Ausführen des SetUps um die Auswertung der Attribute. Hier der konkrete Code aus der Basisklasse:

...
 
[SetUp]
public virtual void SetUp()
{
    if (IsOnMethodSetupTruncateAll())
        _nHibernateHelper.TruncateAll();
 
    ...
}
 
private bool IsOnMethodSetupTruncateAll()
{
    foreach (Attribute attribute in GetType().GetCustomAttributes(true))
        if (attribute.GetType() == typeof(TruncateAllTablesAttribute))
            _onMethodSetupTruncateAll = ((TruncateAllTablesAttribute)attribute).Value;
 
    return _onMethodSetupTruncateAll;
}
 
...

Der Vollständigkeit halber hier noch der Code für ein Attribut, wobei die MSDN das Thema Attribute hervorragend abdeckt

public class TruncateAllTablesAttribute : Attribute
{
    public bool Value = true;
 
    public TruncateAllTablesAttribute(bool value)
    {
        Value = value;
    }
}

enjoyed the post?

Tags:

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.