Как передать java-код параметру из maven для тестирования

Мне нужно передать следующие значения...

exeEvironment (тестовая среда), testGroup (группа в testNG)

из командной строки → POM → TestNG → тестовые примеры.

На основе этих двух сообщений....

передать параметр java из maven

Как передать параметры проверенному тесту TestNG из плагина Surefire Maven?

Я сделал следующую конфигурацию.

В плагине уверенности я попытался выполнить два варианта, ни один из них не работает.

=====

(1)

  <execution>
<id>default-test</id>
    <goals>
        <goal>test</goal>
    </goals>
    <configuration>
        <properties>
            <exeEnvironment>${exeEnvironment}</exeEnvironment>
            <testGroup>${testGroup}</testGroup>
        </properties>
        <suiteXmlFiles>
            <suiteXmlFile>testng.xml</suiteXmlFile>
        </suiteXmlFiles>
    </configuration>
</execution>

(2)

<execution>
<id>default-test</id>
<goals>
    <goal>test</goal>
</goals>
<configuration>
    <systemPropertyVariables> <exeEnvironment>${exeEnvironment}</exeEnvironment> 
        <testGroup>${testGroup}</testGroup> </systemPropertyVariables> 
    <suiteXmlFiles>
        <suiteXmlFile>testng.xml</suiteXmlFile>
    </suiteXmlFiles>
</configuration>
</execution>

В testNG.xml могу ли я использовать переменную testGroup как...

<test name="Web Build Acceptance">
    <groups>
        <run>
            <include name="${testGroup} />
        </run>
    </groups>
    <classes>
        <class name="com.abc.pqr" />
    </classes>
</test>

Это, похоже, не работает, мне нужно определить параметр.


В тестовых случаях я попытался получить переменные двумя способами.... (1)

testEnv = testContext.getSuite().getParameter("exeEnvironment");
testGroup = testContext.getSuite().getParameter("testGroup");

(2)

testEnv = System.getProperty("exeEnvironment");
testGroup = System.getProperty("testGroup");

Ответы

Ответ 1

Это то, что я искал для своего теста автоматизации, и я получил его работу.

Аргумент командной строки

mvn clean test -Denv.USER=UAT -Dgroups=Sniff

Мой Pom Xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>TestNg</groupId>
    <artifactId>TestNg</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
                <configuration>
                    <systemPropertyVariables>
                        <environment>${env.USER}</environment>
                    </systemPropertyVariables>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Тест TestNG

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;


public class TestAuthentication {

    @Test (groups = { "Sniff", "Regression" })
    public void validAuthenticationTest(){
        System.out.println(" Sniff + Regression" + System.getProperty("environment"));
    }

    @Test (groups = { "Regression" },parameters = {"environment"})
    public void failedAuthenticationTest(String environment){
        System.out.println("Regression-"+environment);
    }

    @Parameters("environment")
    @Test (groups = { "Sniff"})
    public void newUserAuthenticationTest(String environment){
        System.out.println("Sniff-"+environment);
    }
}

Это хорошо работает. Кроме того, если вам нужно использовать testng.xml, вы можете указать suiteXmlFile как...

      <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.12.4</version>
            <configuration>
                <systemPropertyVariables>
                    <environment>${env.USER}</environment>
                </systemPropertyVariables>
                <suiteXmlFiles> 
                    <suiteXmlFile>testng.xml</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>

Кроме того, я предпочитаю использовать @Parameters вместо parameters в @Test(), поскольку более поздняя версия устарела.

Ответ 2

Perfect.

Самый простой способ передать переменную из POM.xml в ABC.java

pom.xml

<properties>
   <hostName>myhostname.com</hostName>
</properties>

И в ABC.java мы можем назвать это из системных свойств, подобных этому

System.getProperty("hostName")

Ответ 3

Вам не нужно ничего определять для групп в testng xml или pom, поддержка встроена. Вы можете просто указать группы в строке cmd http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html#groups

Надеюсь, что это поможет.

Изменить 2:

Хорошо.. здесь еще один вариант... Внедрить IMethodInterceptor

Определите свое настраиваемое свойство. Используйте -Dcustomproperty = groupthatneedstoberun в вызове командной строки.

В вызове перехвата просматривайте все методы.. что-то в этом эффекте.

System.getProperty("customproperty");
for(IMethodInstance ins : methods) {
    if(ins.getMethod().getGroups()) contains group)
        Add to returnedVal;
    }
return returnedVal;

Добавьте это в список слушателей в вашем xml.

Ответ 4

Передача параметров, таких как браузер и другие, может быть выполнена следующим образом:

<properties>    
    <BrowserName></BrowserName>
    <TestRunID></TestRunID>
</properties>



        <!-- Below plug-in is used to execute tests -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>
                <suiteXmlFiles>
                    <suiteXmlFile>src/test/resources/${testXml}</suiteXmlFile>
                </suiteXmlFiles>
                <systemPropertyVariables>
                  <browserName>${BrowserName}</browserName>
                    <testRunID>${TestRunID}</testRunID> 
                </systemPropertyVariables>
            </configuration>
            <executions>
                <execution>
                    <id>surefire-it</id>
                    <phase>integration-test</phase>
                    <goals>
                        <goal>test</goal>
                    </goals>
                    <configuration>
                        <skip>false</skip>
                        <testFailureIgnore>true</testFailureIgnore>
                    </configuration>
                </execution>
            </executions>
        </plugin>

и для этого в java-коде используйте это:

 public static final String Browser_Jenkin=System.getProperty("BrowserName");
    public static final String TestRunID=System.getProperty("TestRunID");

  public static String browser_Setter()
    {
        String value=null;
        try {
            if(!Browser_Jenkin.isEmpty())
            {
                value = Browser_Jenkin;
            }
        } catch (Exception e) {
            value =propObj.getProperty("BROWSER");
        }
        return value;   
    }

    public static String testRunID_Setter()
    {
        String value=null;
        try {
            if(!TestRunID.isEmpty())
            {
                value = TestRunID;
            }
        } catch (Exception e) {
            value =propObj.getProperty("TEST_RUN_ID");
        }
        return value;   
    }

Ответ 5

Вам не нужно использовать переменные среды или редактировать pom.xml, чтобы использовать их.

Цели и опции для Invoke Maven 3 в разделе Build принимают параметр. Попробуйте это (при условии, что вы параметризировали сборку):

Invoke Maven 3
  Goals and options = test -Denv=$PARAM_ENV -Dgroup=$PARAM_GROUP