GP Coder

Trang chia sẻ kiến thức lập trình Java

  • Java Core
    • Basic Java
    • OOP
    • Exception Handling
    • Multi-Thread
    • Java I/O
    • Networking
    • Reflection
    • Collection
    • Java 8
  • Design pattern
    • Creational Pattern
    • Structuaral Pattern
    • Behavior Pattern
  • Web Service
    • SOAP
    • REST
  • JPA
  • Java library
    • Report
    • Json
    • Unit Test
  • Message Queue
    • ActiveMQ
    • RabbitMQ
  • All
Trang chủ Java library Unit Test Làm thế nào để chạy lại một failed Test trong JUnit?

Làm thế nào để chạy lại một failed Test trong JUnit?

Đăng vào 21/03/2019 . Được đăng bởi GP Coder . 3802 Lượt xem . Toàn màn hình

Đôi khi chúng ta gặp một số vấn đề ngoài ý muốn khi thực thi Unit test như lỗi kết nối internet, kết nối database, thiếu tài nguyên, … dẫn đến test case của chúng ta bị fail. Trong những trường hợp đó, chúng ta mong muốn có thể thực thi lại các test case một cách tự động. Nhưng bằng cách nào chúng ta có thể làm được điều này với JUnit? Chúng ta sẽ cùng tìm hiểu trong phần tiếp theo của bài viết này.

Nội dung

  • 1 Làm thế nào để chạy lại một failed Test trong JUnit?
  • 2 Ví dụ Retry Failed Tests trong JUnit

Làm thế nào để chạy lại một failed Test trong JUnit?

Trong bài viết Đơn giản hóa Unit Test với JUnit Rule tôi đã giới thiệu với các bạn về Rule trong JUnit, cách sử dụng các Rule được hỗ trợ sẵn trong JUnit và cách tự viết một Rule.

Đối với tình huống này, chúng ta có thể tự viết một custom Rule implements một class TestRule và override phương thức evaluate() để viết code xử lý retry test mỗi khi test bị fail.

Ví dụ Retry Failed Tests trong JUnit

Tạo custom Rule để cố gắng thực thi với một số lần được chỉ định (numberOfRetryTimes) và xác định thời gian chờ trước khi thử lại (delayInMiliseconds).


package com.gpcoder.junit.retry;

import java.util.concurrent.TimeUnit;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RetryRule implements TestRule {
	private int numberOfRetryTimes;
	private int delayInMiliseconds;

	public RetryRule(int numberOfRetryTimes, int delayInMiliseconds) {
		this.numberOfRetryTimes = numberOfRetryTimes;
		this.delayInMiliseconds = delayInMiliseconds;
	}

	public Statement apply(Statement base, Description description) {
		return statement(base, description);
	}

	private Statement statement(final Statement base, final Description description) {
		System.out.println(String.format("\nExecuting test: %s()", description.getMethodName()));
		return new Statement() {
			@Override
			public void evaluate() throws Throwable {
				Throwable caughtThrowable = null;

				// Implement retry logic here
				for (int i = 0; i < numberOfRetryTimes; i++) {
					try {
						base.evaluate();
						return;
					} catch (Throwable t) {
						caughtThrowable = t;
						System.out.println(String.format("%s : run %d failed.", description.getDisplayName(), (i + 1)));
					}
					delay(delayInMiliseconds);
				}
				System.out.println(String.format("%s : giving up after %d failures.\n", description.getDisplayName(), numberOfRetryTimes));
				throw caughtThrowable;
			}
		};
	}
	
	private static void delay(int delayInMiliseconds) throws InterruptedException {
		System.out.println("Waiting for retry next time");
		TimeUnit.MICROSECONDS.sleep(delayInMiliseconds);
	}
}

Viết class test bao gồm 2 phương thức:

  • getData() : phương thức này được thực thi thành công sau khi thử lại 2 lần.
  • alwaysFailed(): phương thức này thực thi luôn bị fail.

package com.gpcoder.junit.retry;

import static org.junit.Assert.assertEquals;

import java.net.ConnectException;

import org.junit.Rule;
import org.junit.Test;

class ThirdPartyApi {
	
	private static int retryCall = 0;

	public static String getData() throws ConnectException {
		if (retryCall < 2) {
			retryCall++;
			throw new ConnectException("Cannot retrieve data. Please try again");
		}
		return "gpcoder.com";
	}
	
	public static String alwaysFailed() throws ConnectException {
		if (true) {
			throw new ConnectException("Cannot retrieve data. Please try again");
		}
		return "gpcoder.com";
	}
}

public class RetryRuleTest {

	@Rule
	public RetryRule retryRule = new RetryRule(3, 10);

	@Test
	public void getDataTest() throws ConnectException {
		assertEquals("gpcoder.com", ThirdPartyApi.getData());
	}
	
	@Test
	public void alwaysFailedTest() throws ConnectException {
		assertEquals("gpcoder.com", ThirdPartyApi.alwaysFailed());
	}
}

Kết quả test:


Executing test: alwaysFailedTest()
alwaysFailedTest(com.gpcoder.junit.retry.RetryRuleTest) : run 1 failed.
Waiting for retry next time
alwaysFailedTest(com.gpcoder.junit.retry.RetryRuleTest) : run 2 failed.
Waiting for retry next time
alwaysFailedTest(com.gpcoder.junit.retry.RetryRuleTest) : run 3 failed.
Waiting for retry next time
alwaysFailedTest(com.gpcoder.junit.retry.RetryRuleTest) : giving up after 3 failures.


Executing test: getDataTest()
getDataTest(com.gpcoder.junit.retry.RetryRuleTest) : run 1 failed.
Waiting for retry next time
getDataTest(com.gpcoder.junit.retry.RetryRuleTest) : run 2 failed.
Waiting for retry next time

5.0
04
Nếu bạn thấy hay thì hãy chia sẻ bài viết cho mọi người nhé! Và Donate tác giả

Shares

Chuyên mục: Unit Test Được gắn thẻ: JUnit

JUnit – Custom Hamcrest Matchers
Làm thế nào để lắng nghe các sự kiện mỗi khi một test được thực thi trong JUnit?

Có thể bạn muốn xem:

  • Giới thiệu JUnit (04/03/2019)
  • Mockito – Annotations (28/03/2019)
  • Đơn giản hóa Unit Test với JUnit Rule (11/03/2019)
  • JUnit – Parameterized Test (08/03/2019)
  • JUnit – Hamcrest Matchers (14/03/2019)

Bình luận

bình luận

Tìm kiếm

Bài viết mới

  • Clean code 13/01/2024
  • Giới thiệu CloudAMQP – Một RabbitMQ server trên Cloud 02/10/2020
  • Kết nối RabbitMQ sử dụng Web STOMP Plugin 19/06/2020
  • Sử dụng publisher confirm trong RabbitMQ 16/06/2020
  • Sử dụng Dead Letter Exchange trong RabbitMQ 13/06/2020

Xem nhiều

  • Hướng dẫn Java Design Pattern – Factory Method (98636 lượt xem)
  • Hướng dẫn Java Design Pattern – Singleton (98311 lượt xem)
  • Giới thiệu Design Patterns (88857 lượt xem)
  • Lập trình đa luồng trong Java (Java Multi-threading) (87109 lượt xem)
  • Giới thiệu về Stream API trong Java 8 (84473 lượt xem)

Nội dung bài viết

  • 1 Làm thế nào để chạy lại một failed Test trong JUnit?
  • 2 Ví dụ Retry Failed Tests trong JUnit

Lưu trữ

Thẻ đánh dấu

Annotation Authentication Basic Java Behavior Pattern Collection Creational Design Pattern Cấu trúc điều khiển Database Dependency Injection Design pattern Eclipse Exception Executor Service Google Guice Gson Hibernate How to Interceptor IO Jackson Java 8 Java Core JDBC JDK Jersey JMS JPA json JUnit JWT Message Queue Mockito Multithreading OOP PowerMockito RabbitMQ Reflection Report REST SOAP Structuaral Pattern Swagger Thread Pool Unit Test Webservice

Liên kết

  • Clean Code
  • JavaTpoint
  • Refactoring Guru
  • Source Making
  • TutorialsPoint
  • W3Schools Online Web Tutorials

Giới thiệu

GP Coder là trang web cá nhân, được thành lập với mục đích lưu trữ, chia sẽ kiến thức đã học và làm việc của tôi. Các bài viết trên trang này chủ yếu về ngôn ngữ Java và các công nghệ có liên quan đến Java như: Spring, JSF, Web Services, Unit Test, Hibernate, SQL, ...
Hi vọng góp được chút ít công sức cho sự phát triển cộng đồng Coder Việt.

Donate tác giả

Tìm kiếm các bài viết của GP Coder với Google Search

Liên hệ

Các bạn có thể liên hệ với tôi thông qua:
  • Trang liên hệ
  • Linkedin: gpcoder
  • Email: contact@gpcoder.com
  • Skype: ptgiang56it

Follow me

Copyright 2025 © GP Coder · All Rights Reserved · Giới thiệu · Chính sách · Điều khoản · Liên hệ ·

Share

Blogger
Delicious
Digg
Email
Facebook
Facebook messenger
Flipboard
Google
Hacker News
Line
LinkedIn
Mastodon
Mix
Odnoklassniki
PDF
Pinterest
Pocket
Print
Reddit
Renren
Short link
SMS
Skype
Telegram
Tumblr
Twitter
VKontakte
wechat
Weibo
WhatsApp
X
Xing
Yahoo! Mail

Copy short link

Copy link