JUnit 5 @BeforeEach注解示例

JUnit 5 @BeforeEach注解是JUnit 4中注解的替换。@Before它用来表示被注解的方法应该@Test在当前类中的每个方法之前执行

@BeforeEach注解用法

注解方法@BeforeEach如下:

@BeforeEach
public void initEach(){
	System.out.println("Before Each initEach() method called");
}

@BeforeEach 带注解的方法一定不能是静态方法,否则将引发运行时错误。

org.junit.platform.commons.JUnitException: @BeforeEach method 'public static void com.how2codex.junit5.examples.JUnit5AnnotationsExample.initEach()' must not be static.
	at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.assertNonStatic(LifecycleMethodUtils.java:73)
	at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.lambda$findBeforeEachMethods$2(LifecycleMethodUtils.java:54)
	at java.util.ArrayList.forEach(ArrayList.java:1249)
	at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1080)
	at org.junit.jupiter.engine.descriptor.LifecycleMethodUtils.findBeforeEachMethods(LifecycleMethodUtils.java:54)

@BeforeEach注解示例

让我们举个例子。我使用了一Calculator类并添加了一种add方法。我将使用@RepeatedTest注解对其进行5次测试。此注解将导致add测试运行5次。对于测试方法的每次运行,带@BeforeEach注解的方法也应每次运行。

package com.how2codex.junit5.examples;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

@RunWith(JUnitPlatform.class)
public class BeforeEachTest {

	@DisplayName("Add operation test")
	@RepeatedTest(5)
	void addNumber(TestInfo testInfo, RepetitionInfo repetitionInfo) {
		System.out.println("Running test -> " + repetitionInfo.getCurrentRepetition());
		Assertions.assertEquals(2, Calculator.add(1, 1), "1 + 1 should equal 2");
	}
	
	@BeforeAll
	public static void init(){
		System.out.println("BeforeAll init() method called");
	}
	
	@BeforeEach
	public void initEach(){
		System.out.println("BeforeEach initEach() method called");
	}
}

其中Calculator类是:

package com.how2codex.junit5.examples;

public class Calculator 
{
	public int add(int a, int b) {
		return a + b;
	}
}

现在执行测试,您将看到以下控制台输出:

BeforeAll init() method called
BeforeEach initEach() method called

BeforeEach initEach() method called
Running test -> 1

BeforeEach initEach() method called
Running test -> 2

BeforeEach initEach() method called
Running test -> 3

BeforeEach initEach() method called
Running test -> 4

BeforeEach initEach() method called
Running test -> 5

显然,每个测试方法调用都会调用一次带@BeforeEach注解的initEach()方法。

学习愉快!

saigon has written 1440 articles

Leave a Reply