如何自定义Junit测试用例调用功能

时间:2012-02-08 10:22:54

标签: java selenium junit

我不希望Junit按顺序调用我的测试方法/ selenium测试用例。但是我想要执行特定的测试用例,或者应该根据我的需要调用它。

示例代码:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;


public class demo2 {
    Selenium selenium;

    @Before
    public void setUp() throws Exception {
        selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.co.in/");
        selenium.start();
        selenium.setTimeout("6000");
    }

    @Test
    public void test_3() throws Exception {
        selenium.open("/");
        selenium.type("q", "3");
    }
    @Test
    public void test_4() throws Exception {
        selenium.open("/");
        selenium.type("q", "4");
    }

    @After
    public void tearDown() throws Exception {
            selenium.stop();
    }
}

注意

我希望方法test_3,test_4 ....应该根据条件调用。

4 个答案:

答案 0 :(得分:3)

您可以使用JUnit中的Assume类。您可以在http://junit.org/apidocs/org/junit/Assume.html中阅读更多内容以供使用。

答案 1 :(得分:2)

您可以使用Assume

assumeTrue(conditionIsFulfilled)

来自doc:

  

失败的假设并不意味着代码被破坏,而是代码   test没有提供有用的信息。默认的JUnit运行器处理   忽略失败假设的测试。自定义跑步者可能会表现出来   不同。

答案 2 :(得分:0)

TestNG允许通过@dependsOnMethods注释。

http://testng.org/doc/documentation-main.html

如果您遇到JUnit,请编写自己的RunsWith,您可以根据需要添加相同或类似的功能。

这里有一个很好的例子:Specifying an order to junit 4 tests at the Method level (not class level)

答案 3 :(得分:0)

不是编写不同的@test,而是可以将这些测试编写为普通的java方法,只编写一个测试。

在该测试中,您可以根据某些条件调用任何方法。

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;


public class demo2 {
    Selenium selenium;

    @Before
    public void setUp() throws Exception {
        selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.co.in/");
        selenium.start();
        selenium.setTimeout("6000");
    }

    @Test
    public void test() throws Exception {
        if(<condition1>){
          method1(selenium);
        }  
        if(<condition2>){
          method2(selenium);
        }  
        if(<condition3>){
          method3(selenium);
        }  
        if(<condition4>){
          method4(selenium);
        }  

    }

    public static void method1(Selenium selenium) 
    throws Exception {
        selenium.open("/");
        selenium.type("q", "1");
    }

    public static void method2(Selenium selenium) 
    throws Exception {
        selenium.open("/");
        selenium.type("q", "2");
    }

    public static void method3(Selenium selenium) 
    throws Exception {
        selenium.open("/");
        selenium.type("q", "3");
    }

    public static void method4(Selenium selenium) 
    throws Exception {
        selenium.open("/");
        selenium.type("q", "4");
    }

    @After
    public void tearDown() throws Exception {
            selenium.stop();
    }
}