1.@Before,@After的例子
在一个测试类中如果含有多个测试方法,如:
public class Address_edit {
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "E:\\TINA\\2018\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}
public void test001() throws InterruptedException {
}
public void test002() throws InterruptedException {
}
@After
public void tearDown() throws Exception {
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
@Before:在跑测试test001,test002时候都会各执行一次@Before部分的代码。
@Beforeclass: 在类中只会被执行一次
@After:释放资源 对于每一个测试方法都要执行一次
@Afterclass:所有测试用例执行完才执行一次
一个JUnit4的单元测试用例执行顺序为:
@BeforeClass -> @Before -> @Test -> @After -> @AfterClass;
每一个测试方法的调用顺序为:
@Before -> @Test -> @After;
2.@Afterclass和@Beforeclass的例子
package com.example.tests;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Login {
public static final String baseUrl = "https://XXXX.XXX.com";
protected static WebDriver driver;
@BeforeClass
public static void setUp() throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "E:\\TINA\\2018\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
//打开微关爱网页
driver.get(baseUrl);
System.out.println("打开网址时的页面名称: " + driver.getTitle());
//窗口最大化
driver.manage().window().maximize();
Thread.sleep(2000);
//根据id获取登录的控件
WebElement Login = driver.findElement(By.xpath("//div[@class='personal-navigation-container hidden-phone']//ul//li[@class='list-item sign-in']/a"));
Login.click();
Thread.sleep(2000);
//输入用户名和密码
driver.navigate().refresh();
WebElement Username = driver.findElement(By.xpath("//div[@class='control-group login-input']//input[@class='field']"));
Thread.sleep(2000);
WebElement Password = driver.findElement(By.id("_59_WAR_forgecartportlet_password"));
WebElement Login_botton = driver.findElement(By.xpath("//button[@type='submit']"));
Username.clear();
Username.sendKeys("XXXX@YYYY.com");
Password.sendKeys("XXXX");
Login_botton.click();
System.out.println("登陆后的页面名称: " + driver.getTitle());
}
@AfterClass
public static void tearDown() throws Exception {
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class Address_Test extends Login {
@Test
//添加新地址
public void test001() throws InterruptedException {
}
}
原文:https://blog.csdn.net/dingjiajia_949/article/details/80183828