Can a JUnit testmethod have a argument?

后端 未结 4 734
慢半拍i
慢半拍i 2020-12-09 08:57
import java.util.regex.Pattern;

public class TestUI {
    private static Pattern p = Pattern.compile(\"^[A-Za-z0-9()+-]+$\");

    public static void main(String[]          


        
相关标签:
4条回答
  • 2020-12-09 09:36

    yes, it can. recently i started zohhak project. it lets you write:

    @TestWith({
       "25 USD",
       "38 GBP",
       "null"
    })
    public void testMethod(Money money) {
       ...
    }
    
    0 讨论(0)
  • 2020-12-09 09:43

    You should take a look at parameterized unit tests (introduced in JUnit 4).

    Daniel Mayer's blog has an example of this.

    Another, more simple example is on mkyong's webpage

    0 讨论(0)
  • 2020-12-09 09:57

    Yes you can with the Theories Runner in JUnit 4.4

    @RunWith(Theories.class)
    public class TheorieTest {
    
       @DataPoints
       public static String[] strings={"a","b","c","d","e"};
    
       private static Pattern p = Pattern.compile("^[A-Za-z0-9()+-]+$");
    
       @Theory
       public void stringTest(String x) {
          assertTrue("string " + x + " should match but does not", p.matcher(x).matches());
    
       }
     }
    

    For more details:

    • Junit 4.4 Release Notes
    • Blog
    0 讨论(0)
  • 2020-12-09 09:57

    You can't directly pass parameters to test methods with JUnit. TestNG allows it, though:

    //This method will provide data to any test method that declares that its Data
    // Provider is named "test1"
    @DataProvider(name = "test1")
    public Object[][] createData1() {
     return new Object[][] {
       { "Cedric", new Integer(36) },
       { "Anne", new Integer(37)},
     };
    }
    
    //This test method declares that its data should be supplied by the Data Provider
    //named "test1"
    @Test(dataProvider = "test1")
    public void verifyData1(String n1, Integer n2) {
     System.out.println(n1 + " " + n2);
    }
    

    will print:

    Cedric 36
    Anne 37
    
    0 讨论(0)
提交回复
热议问题