应该在这样的声明中初始化类字段吗?
public class SomeTest extends TestCase
{
private final List list = new ArrayList();
public void testPopulateList()
{
// Add stuff to the list
// Assert the list contains what I expect
}
}或者在setUp()中是这样的?
public class SomeTest extends TestCase
{
private List list;
@Override
protected void setUp() throws Exception
{
super.setUp();
this.list = new ArrayList();
}
public void testPopulateList()
{
// Add stuff to the list
// Assert the list contains what I expect
}
}我倾向于使用第一种形式,因为它更简洁,并允许我使用最后的字段。如果我不需要为设置使用setUp()方法,我是否应该继续使用它,为什么?
Clarification: JUnit将为每个测试方法实例化测试类一次。这意味着list将在每个测试中创建一次,不管我在哪里声明它。这也意味着测试之间不存在时间依赖关系。因此,使用setUp()似乎没有好处。但是,JUnit常见问题中有许多在setUp()中初始化空集合的示例,因此我认为一定有原因。
发布于 2018-08-12 20:43:51
final (永不更改)中初始化。不依赖于模拟的测试可能如下所示:
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()
...
}
}具有要隔离的依赖项的测试可能如下所示:
@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()
...
}
}https://stackoverflow.com/questions/512184
复制相似问题