Best Practice: Initialize JUnit class fields in setUp() or at declaration?

前端 未结 9 1420
走了就别回头了
走了就别回头了 2020-12-07 09:20

Should I initialize class fields at declaration like this?

public class SomeTest extends TestCase
{
    private final List list = new ArrayList();

    publi         


        
9条回答
  •  悲哀的现实
    2020-12-07 10:17

    • The constant values (uses in fixtures or assertions) should be initialized in their declarations and final (as never change)

    • the object under test should be initialized in the setup method because we may set things on. Of course we may not set something now but we could set it later. Instantiating in the init method would ease the changes.

    • dependencies of the object under test if these are mocked, should not even be instantiated by yourself : today the mock frameworks can instantiate it by reflection.

    A test without dependency to mock could look like :

    public class SomeTest {
    
        Some some; //instance under test
        static final String GENERIC_ID = "123";
        static final String PREFIX_URL_WS = "http://foo.com/ws";
    
        @Before
        public void beforeEach() {
           some = new Some(new Foo(), new Bar());
        } 
    
        @Test
        public void populateList()
             ...
        }
    }
    

    A test with dependencies to isolate could look like :

    @RunWith(org.mockito.runners.MockitoJUnitRunner.class)
    public class SomeTest {
    
        Some some; //instance under test
        static final String GENERIC_ID = "123";
        static final String PREFIX_URL_WS = "http://foo.com/ws";
    
        @Mock
        Foo fooMock;
    
        @Mock
        Bar barMock;
    
        @Before
        public void beforeEach() {
           some = new Some(fooMock, barMock);
        }
    
        @Test
        public void populateList()
             ...
        }
    }
    

提交回复
热议问题