[Software testing] Which one is more advantageous for automated testing, Java or Python?

Java or Python for automated testing, which one has more advantages? Both languages ​​are very popular languages, so technically it's hard to say which one is good and which one is bad. Because whether it is good or not depends on the environment and requirements of use. Just like living in China, if you speak English every day, others will say that you are "twittering again"? But if you go to English-speaking countries such as the United Kingdom and the United States, it will be difficult to communicate if you continue to speak Chinese. Therefore, what language to use depends on the environment. It is meaningless to say whether the language is good or not regardless of the environment!

 language features

1. Java language features

Java has the following advantages in automated testing:

  • Strong cross-platform: Java language is a cross-platform language that can run on different operating systems, including Windows, Linux, Mac, etc.
  • A large number of testing frameworks and tools: Java has a wealth of testing frameworks and tools, such as JUnit, TestNG, Selenium, Appium, etc., which can meet different types of automated testing needs.
  • Abundant third-party libraries: Java has many third-party libraries that can be used to easily implement various functions, such as reading and writing files, network communication, image processing, etc.
  • Object-Oriented Programming: Java is an object-oriented programming language that can better organize code and manage test cases, improve code maintainability and scalability.
  • Strongly typed language: Java is a strongly typed language, which can detect type errors at compile time and improve the robustness and reliability of the code.

2. Python language features

The advantages of Python for automated testing are as follows:

  • Easy to learn: Python language is easy to learn, the syntax is concise and clear, it is easy to learn, and does not require much programming experience.
  • High efficiency: Python has a high development efficiency. It has a wealth of third-party libraries and modules, which can quickly complete automated test development tasks.
  • Cross-platform: Python can run on multiple platforms, including Windows, Linux, MacOS, etc., which can facilitate cross-platform automated testing.
  • A large number of library support: Python has a large number of third-party library support, such as Selenium, PyAutoGUI, Requests, etc., which can facilitate various types of automated testing such as Web, GUI, and API.
  • Community support: Python has a huge community support, and developers can obtain a large number of documents, tutorials and solutions from the community, which can quickly solve problems encountered.
  • Strong readability: Python code is very readable, and the code is highly readable and easy to maintain and modify.
  • Open source and free: Python is a completely open source language and is free to use, which reduces the cost of testing.
  • To sum up: Python language has more advantages in learning, but Java has more advantages in large-scale project development. So it only depends on the individual ability and the actual needs of the enterprise.

 From the realization of automated testing technology

This part of the content will explain the difference between the two from the realization technology of Web automated test script, APP automated test script and interface automated test script:

1. Write Web automation test scripts in Java

To write Selenium automation scripts in Java, you need to install the following tools and environments first:

JDK: Java Development Kit, a toolkit for developing Java programs.

Eclipse: A Java development tool that can be used to write Java programs.

Selenium WebDriver: A tool for automated testing.

Browser driver: Different browsers need corresponding browser drivers, such as Chrome needs ChromeDriver.

next.

We can write Selenium automation scripts for Java by following these steps:

  • Create a Java project and import the jar packages related to Selenium WebDriver.
  • Write test cases, including test steps and assertions.
  • Create a WebDriver object and specify the browser driver.
  • Execute the test case.
  • Output test results.

The following is a simple Java example for writing Selenium automation scripts:

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.testng.Assert;
import org.testng.annotations.*;
 
public class TestDemo {
    private WebDriver driver;
 
    @BeforeTest
    public void setUp() {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }
 
    @Test
    public void test() {
        driver.get("https://www.google.com");
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys("Selenium");
        searchBox.submit();
        Assert.assertEquals(driver.getTitle(), "Selenium - Google 搜索");
    }
 
    @AfterTest
    public void tearDown() {
        driver.quit();
    }
}

In this example, use ChromeDriver as the browser driver, open the Google homepage, enter the keyword "Selenium", and submit the search. We then assert whether the title of the search results page is "Selenium - Google Search". Finally close the browser.

2. Python writes web automation test scripts

Following are the basic steps to write Selenium automation scripts using Python:

  • Install Python and Selenium libraries: First you need to install Python and Selenium libraries. The Selenium library can be installed using the pip command: pip install selenium.
  • Download the browser driver: Selenium needs a browser driver to control the browser. You can download the corresponding driver according to the browser version you use. For example, if you use the Chrome browser, you can download the corresponding version of the driver from the ChromeDriver official website.
  • Write Python scripts: Write Python scripts to control browsers to perform automated testing operations. Here is a simple example script:
from selenium import webdriver
 
# 创建Chrome浏览器对象
driver = webdriver.Chrome('/path/to/chromedriver')
 
# 打开网页
driver.get('http://www.baidu.com')
 
# 在搜索框中输入关键字
search_box = driver.find_element_by_name('wd')
search_box.send_keys('Python Selenium')
 
# 点击搜索按钮
search_button = driver.find_element_by_id('su')
search_button.click()
 
# 关闭浏览器
driver.quit()

Run the Python script: save the script and run it in the terminal. If everything is fine, the browser will automatically open and perform automated testing operations.

It is important to note that Selenium's Python API is slightly different from APIs in other languages, so you need to check the Python API documentation to learn more.

3. Java's appium automated test script

The following is an example of an Appium automated test script written in Java:

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
 
public class AppiumTest {
    AppiumDriver<MobileElement> driver;
 
    @BeforeTest
    public void setup() throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("deviceName", "Android Emulator");
        capabilities.setCapability("platformName", "Android");
        capabilities.setCapability("appPackage", "com.example.android");
        capabilities.setCapability("appActivity", "com.example.android.MainActivity");
        capabilities.setCapability("noReset", true);
        driver = new AndroidDriver<>(new URL("http://0.0.0.0:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }
 
    @Test
    public void testApp() {
        // 在这里编写测试用例
        MobileElement element = driver.findElementById("com.example.android:id/button");
        element.click();
    }
 
    @AfterTest
    public void tearDown() {
        driver.quit();
    }
}

In the above code, an AppiumDriver object is first defined, and then some necessary parameters are set in the setup() method, such as device name, platform name, application package name, and startup activity. Next, we wrote the test case in the testApp() method which clicks a button.

Finally, the driver is shut down in the tearDown() method.

However, it should be noted that the @BeforeTest and @AfterTest annotations are used in the coding to run the setup() and tearDown() methods before and after the test respectively, and the @Test annotation is also used to mark the test cases.

4. Python writes test scripts for appium

Here is an example script for automated testing using Python and Appium:

from appium import webdriver
from time import sleep
 
# 设置Appium连接参数
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '9'
desired_caps['deviceName'] = 'Android Emulator'
desired_caps['appPackage'] = 'com.example.myapp'
desired_caps['appActivity'] = 'MainActivity'
 
# 启动Appium会话
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
 
# 等待应用启动
sleep(5)
 
# 在文本框中输入内容
text_field = driver.find_element_by_id('com.example.myapp:id/text_field')
text_field.send_keys('Hello, World!')
 
# 点击按钮
button = driver.find_element_by_id('com.example.myapp:id/button')
button.click()
 
# 等待结果出现
sleep(2)
 
# 获取结果文本
result = driver.find_element_by_id('com.example.myapp:id/result').text
print(result)
 
# 关闭Appium会话
driver.quit()
Python

This script starts an Android emulator and runs an application called "com.example.myapp" in it. It finds a textbox and a button in the application, enters text into the textbox and clicks the button. Then it waits 2 seconds for the result to appear, and gets the result from the result text. Finally, it closes the Appium session.

5. Write interface automation test scripts in Java

The following is an example of writing an automated test script for an interface in Java:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
 
public class APITest {
    private String baseUrl = "http://api.example.com";
    private String path = "/user";
    private String token = "your_token";
 
    @BeforeClass
    public void setup() {
        RestAssured.baseURI = baseUrl;
    }
 
    @Test
    public void testGetUserById() {
        String id = "123";
        Response response = RestAssured.given()
                .header("Authorization", "Bearer " + token)
                .when()
                .get(path + "/" + id)
                .then()
                .extract().response();
 
        Assert.assertEquals(response.getStatusCode(), 200);
        Assert.assertEquals(response.jsonPath().get("id"), id);
        Assert.assertEquals(response.jsonPath().get("name"), "John");
    }
 
    @Test
    public void testCreateUser() {
        String requestBody = "{\"name\":\"John\",\"age\":30}";
 
        Response response = RestAssured.given()
                .header("Authorization", "Bearer " + token)
                .header("Content-Type", "application/json")
                .body(requestBody)
                .when()
                .post(path)
                .then()
                .extract().response();
 
        Assert.assertEquals(response.getStatusCode(), 201);
        Assert.assertEquals(response.jsonPath().get("name"), "John");
        Assert.assertEquals(response.jsonPath().get("age"), 30);
    }
 
    @Test
    public void testUpdateUser() {
        String id = "123";
        String requestBody = "{\"name\":\"John\",\"age\":31}";
 
        Response response = RestAssured.given()
                .header("Authorization", "Bearer " + token)
                .header("Content-Type", "application/json")
                .body(requestBody)
                .when()
                .put(path + "/" + id)
                .then()
                .extract().response();
 
        Assert.assertEquals(response.getStatusCode(), 200);
        Assert.assertEquals(response.jsonPath().get("id"), id);
        Assert.assertEquals(response.jsonPath().get("name"), "John");
        Assert.assertEquals(response.jsonPath().get("age"), 31);
    }
 
    @Test
    public void testDeleteUser() {
        String id = "123";
 
        Response response = RestAssured.given()
                .header("Authorization", "Bearer " + token)
                .when()
                .delete(path + "/" + id)
                .then()
                .extract().response();
 
        Assert.assertEquals(response.getStatusCode(), 204);
    }
}
Java

In this example, the RestAssured library is used to send HTTP requests and parse responses. In the @BeforeClass annotated method, the base API URL is also set. In each test method, send an HTTP request and make assertions on the response to ensure the correctness of the API.

6. Write interface automation test scripts in Python

The following is an example of a simple Python interface automation test script:

import requests
 
# 定义接口请求地址和参数
url = "http://example.com/api"
params = {"key": "value"}
 
# 发送请求并获取响应
response = requests.get(url, params=params)
 
# 验证响应状态码
if response.status_code == 200:
    print("接口请求成功!")
else:
    print("接口请求失败!")
 
# 验证响应数据
expected_data = {"code": 200, "message": "success"}
actual_data = response.json()
if actual_data == expected_data:
    print("接口响应数据正确!")
else:
    print("接口响应数据错误!")
Python

In the above example, use the requests library to send a GET request, verify the response status code through status_code, use the json() method to obtain the response data, and compare it with the expected data to verify whether the interface response data is correct. You can further improve and optimize the test script according to your own needs and actual interface conditions.

To sum up: Java coding is relatively more complicated, and python coding is more concise. So if you want to master automated testing faster, python is the first choice.

Finally, I would like to thank everyone who has read my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, you can take it away if you need it:

insert image description here

Software testing interview applet

The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!

The following interview question sections are covered:

1. Basic theory of software testing, 2. web, app, interface function testing, 3. network, 4. database, 5. linux

6. web, app, interface automation, 7. performance testing, 8. programming basics, 9. hr interview questions, 10. open test questions, 11. security testing, 12. computer basics

These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too!  

Guess you like

Origin blog.csdn.net/nhb687095/article/details/132379635