maandag 4 oktober 2010

What to place in @Before/ setUp method

Last week, I attended a TDD course by @unclebobmartin, and one of te practices I saw a lot was putting ALL test setup code in the setup method. This resulted in some quote like “all test methods should ideally be two lines long”. This leads to code like this:


@Before public void setUp(){
//setting up common test fixture ...
//manipulating test fixture for test1 running ...
//manipulating test fixture to have test2 running ...
}

@Test public void test1(){
//execute ...
//verify ...
}


Personally, I disagree with this statement as I believe no code should be in the setup method that is not relevant for all off the tests in the test body, so my motto is more like: “all test methods should ideally be three lines long: a setup part, an execution part and a verification part.”  It makes a test understandable by just looking at the test method itself, and that is essential if you want to have code that is easy to maintain. This leads to the following code which is generally a lot cleaner:



@Before public void setUp(){
//setting up common test fixture ...
}

@Test public void test1(){
//manipulating test fixture to have test1 running
//execute ...
//verify ...
}