Community
Participate
Working Groups
Triggered by a post to the JUnit mailing list: http://groups.yahoo.com/group/junit/message/15085 Quoting: The refactoring I've wanted most is Replace Query with Fixture. For example, from: public void testA() { Component comp = new Component(5); assertEquals(6, comp.successor()); } public void testB() { Component comp = new Component(5); assertEquals(4, comp.predecessor()); } I can automatically Extract Method to get: public void testA() { Component comp = theComponent(); assertEquals(6, comp.successor()); } public void testB() { Component comp = theComponent(); assertEquals(4, comp.predecessor()); } private Component theComponent() { return new Component(5); } But I want the next step automatically, as well: public void setUp() { Component fComp = new Component(5); } public void testA() { assertEquals(6, fComp.successor()); } public void testB() { assertEquals(4, fComp.predecessor()); } This would have to be implemented for JUnit 3 or 4.
I think there is an easier solution: The "Convert Local Variable to Field" refactoring could offer an additional "initialize in setUp" option.
See bug 39904
bug 39904 goes a long way. But, especially when using JMock, I often find myself wanting to move not just the first line of initialization, but a set of lines, like: fLaunchConfiguration = mockFor(ILaunchConfiguration.class); fLaunchConfiguration.stubs(); Come to think of it, given a fix for 39904, I can think of a workaround for this problem, so I'll let this depend on 39904.
A quick assist might be better here.
Actually, with JUnit 4, it gets a lot easier: @Before public void theComponent() { fComp = new Component(5); }
(In reply to comment #5) > Actually, with JUnit 4, it gets a lot easier: > @Before > public void theComponent() { > fComp = new Component(5); > } Easier in which way?
Easier in this way: for JUnit 4 tests, it is only necessary to mark the method as "@Before", rather than try to move the logic into the setUp() method.
I see - you don't need to move code into a possibly already existing method. So what needs to be done for JUnit 4 is - extract method - mark the method with the @Before annotation - remove the method call from the test(s)
Actually, I'm assuming the method is already extracted, so just the two remaining points.