Вступ до тестування в 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);
Працює так само для Set і Map з Java Collections
Об'єкти, створені через .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