JUnit5测试实例大全

Junit 测试实例

以下是常用的JUnit测试示例,涵盖基础到进阶场景,适合学习和日常使用。示例基于JUnit 5(Jupiter),部分兼容JUnit 4。

基础断言测试

@Test
void basicAssertions() {
    assertEquals(4, 2 + 2);
    assertTrue(5 > 3);
    assertNull(null);
    assertNotSame(new Object(), new Object());
}

异常测试

@Test
void expectException() {
    assertThrows(ArithmeticException.class, () -> {
        int result = 1 / 0;
    });
}

超时测试

@Test
void timeoutTest() {
    assertTimeout(Duration.ofSeconds(2), () -> {
        Thread.sleep(1000);
    });
}

参数化测试

@ParameterizedTest
@ValueSource(ints = {1, 3, 5})
void isOdd(int number) {
    assertTrue(number % 2 != 0);
}

动态测试

@TestFactory
Stream dynamicTests() {
    return Stream.of("A", "B", "C")
        .map(text -> DynamicTest.dynamicTest("Test " + text, () -> {
            assertNotNull(text);
        }));
}

测试生命周期钩子

@BeforeEach
void setup() {
    System.out.println("Before each test");
}

@AfterEach
void cleanup() {
    System.out.println("After each test");
}

条件测试

@Test
@EnabledOnOs(OS.MAC)
void onlyOnMac() {
    assertTrue(System.getProperty("os.name").contains("Mac"));
}

嵌套测试

@Nested
class NestedTests {
    @Test
    void innerTest() {
        assertEquals(3, 1 + 2);
    }
}

重复测试

@RepeatedTest(3)
void repeatTest() {
    assertNotEquals(0, Math.random());
}


测试顺序控制

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class OrderedTests {
    @Test @Order(1)
    void firstTest() { /* ... */ }

    @Test @Order(2)
    void secondTest() { /* ... */ }
}


Mockito集成

@Test
void mockTest() {
    List mockList = Mockito.mock(List.class);
    when(mockList.size()).thenReturn(10);
    assertEquals(10, mockList.size());
}


假设条件

@Test
void assumeTest() {
    Assumptions.assumeTrue("DEV".equals(System.getenv("ENV")));
    // 仅在DEV环境下执行
    assertTrue(true);
}


测试接口默认方法

interface Testable {
    default boolean isValid() { return true; }
}

@Test
void testInterfaceDefault() {
    Testable obj = new Testable() {};
    assertTrue(obj.isValid());
}


临时目录支持

@Test
void tempDirTest(@TempDir Path tempDir) throws IOException {
    Path file = tempDir.resolve("test.txt");
    Files.write(file, "Hello".getBytes());
    assertTrue(Files.exists(file));
}


测试私有方法(反射)

@Test
void testPrivateMethod() throws Exception {
    Method method = MyClass.class.getDeclaredMethod("privateMethod");
    method.setAccessible(true);
    assertEquals(42, method.invoke(new MyClass()));
}

分组断言

@Test
void groupedAssertions() {
    assertAll("person",
        () -> assertEquals("John", person.getFirstName()),
        () -> assertEquals("Doe", person.getLastName())
    );
}


测试流式API

@Test
void streamTest() {
    List numbers = Arrays.asList(1, 2, 3);
    assertTrue(numbers.stream().anyMatch(n -> n % 2 == 0));
}


自定义断言消息

@Test
void customMessage() {
    assertEquals(5, 2 + 2, "Math seems broken");
}


测试集合

@Test
void collectionTest() {
    List list = Arrays.asList("a", "b", "c");
    assertIterableEquals(List.of("a", "b", "c"), list);
}


测试Lambda表达式

@Test
void lambdaTest() {
    assertTrue(() -> {
        // 复杂逻辑
        return true;
    });
}

测试超类方法

class Parent {
    protected String getName() { return "Parent"; }
}

@Test
void testParentMethod() {
    Parent obj = new Parent();
    assertEquals("Parent", obj.getName());
}


测试文件操作

@Test
void fileTest() throws IOException {
    Path path = Paths.get("test.txt");
    Files.write(path, "content".getBytes());
    assertLinesMatch(List.of("content"), Files.readAllLines(path));
    Files.delete(path);
}


测试随机行为

@Test
void randomTest() {
    Random random = new Random(42); // 固定种子
    assertEquals(7, random.nextInt(10));
}


测试系统属性

@Test
void systemPropertyTest() {
    System.setProperty("test.key", "value");
    assertEquals("value", System.getProperty("test.key"));
}


测试多线程

@Test
void threadTest() throws InterruptedException {
    AtomicInteger counter = new AtomicInteger();
    Thread thread = new Thread(() -> counter.incrementAndGet());
    thread.start();
    thread.join();
    assertEquals(1, counter.get());
}

以上示例覆盖了单元测试的常见场景,可根据实际需求调整参数和断言逻辑。JUnit 5的完整文档可通过官网进一步查阅。

基于Spring Boot和JUnit的自动化测试实例

以下是基于Spring Boot和JUnit的自动化测试实例,涵盖单元测试、集成测试、Mock测试等常见场景,以代码片段和说明方式呈现。每个例子均遵循Spring Boot测试最佳实践。

基础单元测试(Service层)

@SpringBootTest
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void testCreateUser() {
        User user = new User("test", "[email protected]");
        User savedUser = userService.createUser(user);
        assertNotNull(savedUser.getId());
        assertEquals("test", savedUser.getUsername());
    }
}

模拟Repository层(@MockBean)

@SpringBootTest
public class OrderServiceTest {
    @MockBean
    private OrderRepository orderRepository;

    @Autowired
    private OrderService orderService;

    @Test
    public void testFindOrderById() {
        Order mockOrder = new Order(1L, "PENDING");
        when(orderRepository.findById(1L)).thenReturn(Optional.of(mockOrder));

        Order result = orderService.getOrderById(1L);
        assertEquals("PENDING", result.getStatus());
    }
}

Web层测试(MockMVC)

@WebMvcTest(UserController.class)
public class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    public void testGetUser() throws Exception {
        when(userService.getUser(1L)).thenReturn(new User(1L, "admin"));

        mockMvc.perform(get("/users/1"))
               .andExpect(status().isOk())
               .andExpect(jsonPath("$.username").value("admin"));
    }
}

测试异常处理

@Test
public void testInvalidUserRegistration() {
    User invalidUser = new User("", "invalid-email");
    assertThrows(ValidationException.class, 
        () -> userService.createUser(invalidUser));
}

数据库集成测试(@DataJpaTest)

@DataJpaTest
public class ProductRepositoryTest {
    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private ProductRepository productRepository;

    @Test
    public void testFindByCategory() {
        entityManager.persist(new Product("Laptop", "Electronics"));
        List products = productRepository.findByCategory("Electronics");
        assertEquals(1, products.size());
    }
}

测试配置文件(@TestPropertySource)

@SpringBootTest
@TestPropertySource(locations = "classpath:test.properties")
public class ConfigTest {
    @Value("${app.test.value}")
    private String testValue;

    @Test
    public void testConfigLoad() {
        assertEquals("test123", testValue);
    }
}

异步方法测试

@Test
public void testAsyncOperation() throws Exception {
    CompletableFuture future = asyncService.asyncTask();
    String result = future.get(2, TimeUnit.SECONDS);
    assertEquals("Done", result);
}

测试静态方法(配合PowerMock)

@RunWith(PowerMockRunner.class)
@PrepareForTest(UtilityClass.class)
public class UtilityTest {
    @Test
    public void testStaticMethod() {
        mockStatic(UtilityClass.class);
        when(UtilityClass.generateId()).thenReturn("mock-id");
        assertEquals("mock-id", UtilityClass.generateId());
    }
}

测试Spring Security

@WithMockUser(username = "admin", roles = "ADMIN")
@Test
public void testAdminEndpoint() throws Exception {
    mockMvc.perform(get("/admin"))
           .andExpect(status().isOk());
}

测试REST模板(@RestClientTest)

@RestClientTest(ApiClient.class)
public class ApiClientTest {
    @Autowired
    private MockRestServiceServer server;

    @Autowired
    private ApiClient apiClient;

    @Test
    public void testGetData() {
        server.expect(requestTo("/api/data"))
              .andRespond(withSuccess("{\"id\":1}", MediaType.APPLICATION_JSON));
        
        ApiResponse response = apiClient.fetchData();
        assertEquals(1, response.getId());
    }
}

参数化测试(@ParameterizedTest)

@ParameterizedTest
@ValueSource(strings = {"cat", "dog", "fish"})
public void testStringLength(String input) {
    assertTrue(input.length() > 2);
}

测试事务回滚

@SpringBootTest
@Transactional
public class TransactionTest {
    @Test
    public void testRollback() {
        // 测试方法执行后事务会自动回滚
        userRepository.save(new User("temp", "[email protected]"));
        assertEquals(1, userRepository.count());
    }
}

测试自定义注解

@Test
public void testCustomAnnotation() {
    Method method = MyService.class.getMethod("annotatedMethod");
    assertNotNull(method.getAnnotation(MyAnnotation.class));
}

测试日志输出

@Test
public void testLogOutput() {
    Logger logger = (Logger) LoggerFactory.getLogger(MyService.class);
    MemoryAppender appender = new MemoryAppender();
    appender.start();
    logger.addAppender(appender);

    service.performAction();
    assertTrue(appender.contains("Action performed", Level.INFO));
}

测试Spring Cache

@Test
public void testCacheEvict() {
    service.getData(1L); // 存入缓存
    service.getData(1L); // 应从缓存读取
    verify(repository, times(1)).findById(1L);

    service.clearCache();
    service.getD

你可能感兴趣的:(JUnit5测试实例大全)