TDD: Help with writing Testable Class

╄→尐↘猪︶ㄣ 提交于 2019-12-05 07:54:48

One solution is to not have the constructor do the work:

public class PurchaseOrder
{
    public PurchaseOrder(string newNumber, string newLine)
    {
        NewNumber = newNumber;
        NewLine = newLine;
    }
    // ...
}

Then testing is easy and isolated - you're not testing GetNewNumber and GetNewLine at the same time.

To help using PurchaseOrder you can create a factory method that puts it together:

public static PurchaseOrder CreatePurchaseOrder(string purchaseOrderText)
{
   return new PurchaseOrder(
     GetNewNumber(purchaseOrderText),
     GetNewLine(purchaseOrderText));
}

Instead of making the setters public, make them internal and then make your test assembly InternalsVisibleTo in your main project. That way, your tests can see your internal members, but no-one else can.

In you main project, put something like this;

[assembly: InternalsVisibleTo( "UnitTests" )]

Where UnitTests is the name of your test assembly.

Create a private accessor for your class in the test project and then use the accessor to set the properties for your test. In VS you can create private accessors by right-clicking in the class, choosing Create Private Accessor, and selecting the test project. In your test you then use it like so:

public void NameOfTest()
{
    PurchaseOrder_Accessor order = new PurchaseOrder_Accessor();
    order.NewNumber = "123456";
    order.NewLine = "001";
    Assert.IsTrue(order.IsValid);
}

If you have a default constructor you can do:

public void NameOfTest()
{
    PurchaseOrder order = new PurchaseOrder()
    PurchaseOrder_Accessor accessor =
                new PurchaseOrder_Accessor( new PrivateObject(order) );
    accessor.NewNumber = "123456";
    accessor.NewLine = "001";
    Assert.IsTrue(order.IsValid);
}

I would probably create a new constructor public PurchaseOrder(string newNumber, string newLine). IMO, you're likely to need it anyway.

a little offtopic :)

Using TDD, it`s about writing your unit-tests first, then just write enough code to pass the test and after that do refactoring. By writing your tests first you should exactly know what and maybe how to program to make your code testable!

just my 2 cents...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!