Java 测试入门
Maria Milusheva
Senior Software Engineer
请看:
List<Integer> newList = new ArrayList<Integer>();
newList.add(10);
newList.add(20);
newList.add(30);
更快更短的方式:
List<Integer> newList = List.of(10, 20, 30);
对 Java Collections 的 Set 和 Map 同样适用
用 .of() 创建的对象通常是不可变的(不能修改)
请看以下类:
class Person {
String firstName;
String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String fullName(Person person) {
return firstName + " " + lastName;
}
}
使用 Arguments 传递任意类型的多个参数。
Arguments:可包含任意数量、任意类型的对象。
例如:
Arguments.of(new Person("Monty", "Python"), "Monty Python");
接下来可用于以下 @ParameterizedTest 类型。
@MethodSource 允许向测试传递任意对象。
测试如下:
@ParameterizedTest
@MethodSource("provideNames")
void testFullName(Person person, String expectedFullName) {
assertEquals(person.fullName(person), expectedFullName);
}
用于 @MethodSource 的方法:
private static List<Arguments> provideNames() {
List<Arguments> args = new ArrayList<>();
args.add(Arguments.of(new Person("Robert", "Martin"), "Robert Martin"));
args.add(Arguments.of(new Person("Heinz", "Kabutz"), "Heinz Kabutz"));
return args;
}
注意:方法需为 static
注意:允许多种返回类型;List<Arguments> 最简单
用于 @MethodSource 的方法:
private static List<Arguments> provideNames() {
return List.of(
Arguments.of(new Person("John", "Doe"), "John Doe"),
Arguments.of(new Person("Jane", "Doe"), "Jane Doe"),
Arguments.of(new Person("Alice", "Bob"), "Alice Bob"));
}
考虑以下数据库测试:
@Test void process_savesToInfoStore_whenInfoMessage() { InfoStore infoStore = mock(InfoStore.class); ErrorStore errorStore = mock(ErrorStore.class); MessageProcessor messageProcessor = new MessageProcessor(infoStore, errorStore);messageProcessor.saveMessage("[INFO] Process started.");verify(infoStore).save("[INFO] Process started."); verifyNoInteractions(errorStore); }
可用 @BeforeEach 注解创建每个测试前执行的方法:
import org.junit.jupiter.api.BeforeEach;
要使用它,先将对象声明为字段:
class MessageProcessorTest {
private InfoStore infoStore;
private ErrorStore errorStore;
private MessageProcessor messageProcessor;
在单独的方法中创建每个对象:
@BeforeEach
void setUp() {
this.infoStore = mock(InfoStore.class);
this.errorStore = mock(errorStore.class);
this.messageProcessor = new MessageProcessor(infoStore, errorStore);
}
测试类随后变为:
@Test
void process_savesToInfoStore_whenInfoMessage() {
messageProcessor.process("[INFO] Process started.");
verify(infoStore).save("[INFO] Process started.");
verifyNoInteractions(errorStore);
}
整合如下:
class MessageProcessorTest { private InfoStore infoStore; // 声明字段@BeforeEach void setUp() { this.infoStore = mock(InfoStore.class); // 初始化字段 }@Test void process_savesToInfoStore_whenInfoMessage() { // 使用字段 } }
Java 测试入门