初学appium时发现用junit运行第二条用例的时候会报错发现很多人都遇到此问题。
问题原因:
因为在appium配置的代码部分用的是@Before注释(目前的appium的新手教程中用的都是这个方法),每一次的测试用例执行前都会去执行@Before,导致执行顺序变成了。
@Before >>@Test 1>>@Before>>@Test2。
所以第二条用例直接报错。
解决方式
让@Before中的配置内容只在第一条用例前执行:
将@Before注释改成@BeforeClass注释。注:@BeforeClass必须为static void。
示例代码:
package aibei348_appium;
import static org.junit.Assert.*;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;
import java.io.File;
import java.net.URL;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class Aibei348case {
private static AppiumDriver dr;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
// set up appium
File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, "apps/348");
File app = new File(appDir, "payMainActivity-debug.apk");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("device","Android");
capabilities.setCapability("deviceName","Android");
capabilities.setCapability("CapabilityType", "6.0");
capabilities.setCapability("unicodeKeyboard", "True");
capabilities.setCapability("resetKeyboard", "True");
capabilities.setCapability("noSign","true");
capabilities.setCapability(CapabilityType.PLATFORM, "WINDOWS");
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("appPackage", "com.***.pay");
capabilities.setCapability("noReset", true);
capabilities.setCapability("appActivity", "com.***.demo.activity.MainDemoActivity");
dr = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
@Test
public void A_paydemo() {
WebElement mant = dr.findElement(By.name("***"));
AssertJUnit.assertTrue(mant.getText().contains("***"));
System.out.println("进入收银台");
mant.click();
// dr.quit();
}
@Test
public void B_paydemo_2() throws InterruptedException {
dr.findElement(By.id("com.***.pay:id/appuseridEdit")).sendKeys("啦啦啦");
dr.findElement(By.name("竖屏")).click();
dr.findElement(By.name("***")).click();
dr.findElement(By.id("com.***348.pay:id/et_input_price")).sendKeys("1");
dr.findElement(By.name("确认支付")).click();
dr.findElement(By.className("android.widget.TextView")).click();
Thread.sleep(100);
dr.swipe(187, 1520, 187, 900, 200);
}
//@After
//public void tearDown() throws Exception {
// dr.quit();
//}
}