Chinaunix首页 | 论坛 | 博客
  • 博客访问: 209237
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: Java

2011-03-30 10:58:13

How do I use a test fixture?

(Submitted by: Jeff Nielsen)

A test fixture is useful if you have two or more tests for a common set of objects. Using a test fixture avoids duplicating the code necessary to initialize (and cleanup) the common objects.

Tests can use the objects (variables) in a test fixture, with each test invoking different methods on objects in the fixture and asserting different expected results. Each test runs in its own test fixture to isolate tests from the changes made by other tests. That is, tests don't share the state of objects in the test fixture. Because the tests are isolated, they can be run in any order.

To create a test fixture, declare instance variables for the common objects. Initialize these objects in a public void method annotated with@Before. The JUnit framework automatically invokes any @Before methods before each test is run.

The following example shows a test fixture with a common Collection object.


package junitfaq;

import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;

public class SimpleTest {

private Collection collection;

@Before
public void setUp() {
collection = new ArrayList();
}

@Test
public void testEmptyCollection() {
assertTrue(collection.isEmpty());
}


@Test
public void testOneItemCollection() {
collection.add("itemA");
assertEquals(1, collection.size());
}
}

Given this test, the methods might execute in the following order:

setUp()
testEmptyCollection()
setUp()
testOneItemCollection()

The ordering of test-method invocations is not guaranteed, so testOneItemCollection() might be executed before testEmptyCollection(). But it doesn't matter, because each method gets its own instance of the collection.

Although JUnit provides a new instance of the fixture objects for each test method, if you allocate any external resources in a @Before method, you should release them after the test runs by annotating a method with @After. The JUnit framework automatically invokes any @Aftermethods after each test is run. For example:


package junitfaq;

import org.junit.*;
import static org.junit.Assert.*;
import java.io.*;

public class OutputTest {

private File output;

@Before
public void createOutputFile() {
output = new File(...);
}

@After
public void deleteOutputFile() {
output.delete();
}

@Test
public void testSomethingWithFile() {
...
}
}

With this test, the methods will execute in the following order:


createOutputFile()
testSomethingWithFile()
deleteOutputFile()
阅读(375) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~