参数化的JUnit测试
生活随笔
收集整理的這篇文章主要介紹了
参数化的JUnit测试
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有時,您會遇到一個問題,就是尖叫使用“參數化”測試,而不是多次復制/粘貼相同的方法。 測試方法基本上是相同的,唯一改變的是傳入的數據。在這種情況下,請考慮創建一個利用JUnit中的“ Parameterized ”類的測試用例。
我最近遇到了一個問題,其中我們對電子郵件地址的驗證不允許使用unicode字符。 解決方法非常簡單,更改正則表達式以允許這些字符。 接下來,該測試更改了。 我決定不對每組數據復制/粘貼單獨的方法,而是決定學習Parameterized方法。 結果如下。 數據包括預期結果和要驗證的電子郵件地址。
JUnit測試類
package com.mycompany.client;import static org.junit.Assert.*;import java.util.Arrays;import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters;import com.mycompany.test.TestServiceUtil;/*** Parameterized test case for validating email addresses against a regular expression.* We need to allow unicode characters in the userid portion of the email address, so * these test cases where created to help validate the validateEmailAddress method* in the FieldValidationController class.* * @author mmiller**/ @RunWith(Parameterized.class) public class TestFieldValiationController {@Parameters(name = "{index}: {1} is valid email address = {0}")public static Iterable<Object> data() {return Arrays.asList(new Object[][] { { true, "john@mycomp.com" }, { true, "john123@mycomp.com" },{ true, "j+._%20_-brown@mycomp.com" }, { true, "123@mycomp.com" },{ false, "john brown@mycomp.com" }, { false, "123@mycomp" },{ false, "john^brown@mycomp.com" }, { true , "1john@mycomp.com" },{ false, "john#brown@mycomp.com" }, { false, "john!brown@mycomp.com" },{ false, "john()brown@mycomp.com" }, { false, "john=brown@mycomp.com" },{ true, "joh?.brown@mycomp.com" }, { false, "john.brown@mycomp.co?" },{ true, "johú@mycomp.com" }, { true, "johíáó@mycomp.com" }});}private boolean expected;private String emailAddress;public TestFieldValiationController(boolean expected, String emailAddress) {this.expected = expected;this.emailAddress = emailAddress;TestServiceUtil.getInstance();}@Testpublic void validateEmail() {assertEquals(expected, FieldValidationController.getInstance().validateEmailAddress(emailAddress));} } 希望這可以幫助!
翻譯自: https://www.javacodegeeks.com/2014/03/parameterized-junit-tests.html
總結
以上是生活随笔為你收集整理的参数化的JUnit测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 盖主是什么意思 盖主的解释
- 下一篇: 快速的远程服务测试