简体   繁体   English

如何将java类导入到Robot Framework之类的库中

[英]How to import java class, to Robot Framework like library

I can't understand how to import .jar file, in Robot Framework.我无法理解如何在 Robot Framework 中导入 .jar 文件。

Here is the code:这是代码:

*** Settings ***
Library   MyLibrary

*** Test Cases ***
My Test
    Do Nothing
    Hello    world

and Java:和爪哇:

public class MyLibrary {

    public void hello(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public void doNothing() {
    }

}

After Extracting in .jar, I put in C:\\Python27\\Lib\\site-packages\\MyLibrary and I created empty __init__.py file.在 .jar 中提取后,我放入 C:\\Python27\\Lib\\site-packages\\MyLibrary 并创建了空的__init__.py文件。 After I execute my Robot file with: pybot TestJavaLibrary.robot I get this WARN:在我使用以下命令执行我的机器人文件后: pybot TestJavaLibrary.robot我得到这个警告:

[ WARN ] Imported library 'MyLibrary' contains no keywords.
==============================================================================
TestJavaLibrary
==============================================================================
My Test                                                               | FAIL |
No keyword with name 'Do Nothing' found.

How to use this jar, like external library?如何使用这个 jar,比如外部库?

  1. you need jython to run your tests, it means you need to install jython to run tests.你需要 jython 来运行你的测试,这意味着你需要安装 jython 来运行测试。
  2. no special action is needed when importing your java library.导入 Java 库时不需要特殊操作。
  3. you need to tell jybot where to find your java library or classes.您需要告诉 jybot 在哪里可以找到您的 Java 库或类。
    jybot --pythonpath <the_path_to_your_java_classes> your_tests
    //e.g.   
    jybot --pythonpath c:/test-project/target/classes  your_tests

I have also worked on the same kind of project which required Java class to be called via robot framework.我还从事过相同类型的项目,该项目需要通过机器人框架调用 Java 类。 Here is a short example of importing a Java library:下面是一个导入 Java 库的简短示例:

File : myJavaLibrary.java文件myJavaLibrary.java

public class myJavaLibrary{

    public void my_java_add(int i, int j, int k) {
        if(i+j == k)
            return;
        System.out.println("Invalid Sum");
        assert false;
    }

}

Use command : javac myJavaLibrary.java使用命令:javac myJavaLibrary.java

This will create a .class file in the same directory : myJavaLibrary.class这将在同一目录中创建一个 .class 文件:myJavaLibrary.class

Import this in robot file :在机器人文件中导入:

File: test.robot.txt文件:test.robot.txt

*** Settings ***

Library       myJavaLibrary.java

*** Test Cases ***

User defined Java Test

    My Java Add     5   7   12

You may notice that library myJavaLibrary.java is added in settings section, since robot file is present in the same directory as .class file.您可能会注意到在设置部分添加了库 myJavaLibrary.java,因为机器人文件与 .class 文件位于同一目录中。 You may add the absolute path for the same.您可以添加相同的绝对路径。

You may need to install jython for running the robot file.您可能需要安装 jython 才能运行机器人文件。

Finally use the command:最后使用命令:

jython -m robot test.robot.txt. jython -m 机器人 test.robot.txt。

Final output can be seen in log.html file in the run folder最终输出可以在运行文件夹中的log.html文件中看到

For JAR import:对于 JAR 导入:

Include the absolute path to .jar file in your environmental variable :环境变量中包含 .jar 文件的绝对路径:

Variable Name : CLASSPATH变量名称:类路径

Variable Value : "Absolute path to directory containing Jar"\\*;变量值:“包含 Jar 的目录的绝对路径”\\*;

In this case the process is same for running robot file, and there is no need to include any library.在这种情况下,运行机器人文件的过程是相同的,不需要包含任何库。

Hope this works.希望这有效。

Reference: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html参考: http : //robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html

You have to use jython (jybot).你必须使用 jython (jybot)。 There are other settings like JYTHONPATH.还有其他设置,如 JYTHONPATH。

I figure it out!!我想通了!!

=============env================ ==============环境================

**********Sys Window 10 **********系统窗口 10

First of all,you need install jdk,jython,robot framework首先,你需要安装 jdk、jython、robot 框架

(PS:jython do not need python2.7 or other python sdk.) (PS:jython不需要python2.7或其他python sdk。)

**********For intall **********整体

jdk I use a zip. jdk 我用的是 zip。

jython I use a installer jar 2.7.2b3,double click and use install all model. jython 我使用安装程序 jar 2.7.2b3,双击并使用安装所有模型。

robot I use master download master code zip, then use "jython setup.py install"机器人我使用master下载master code zip,然后使用“jython setup.py install”

I did not add "CLASSPATH" to Windows System ENV "PATH",I'll say reason later.我没有在Windows系统ENV“PATH”中添加“CLASSPATH”,后面我会说原因。

I just added D:\\Tools\\jython2.7\\bin To Windows System ENV "PATH".我刚刚将 D:\\Tools\\jython2.7\\bin 添加到 Windows 系统 ENV“PATH”。

D:\Tools\jython2.7\bin 的目录
2020/03/01  01:29    <DIR>          .
2020/03/01  01:29    <DIR>          ..
2020/03/01  01:29               417 chardetect-script.py
2020/03/01  01:29            74,752 chardetect.exe
2020/03/01  01:27           102,772 easy_install-2.7.exe
2020/03/01  01:27           102,772 easy_install.exe
2020/02/02  11:30         3,979,302 jython.exe
2020/02/02  11:30               282 jython_regrtest.bat
2020/03/01  01:28           102,754 pip.exe
2020/03/01  01:28           102,754 pip2.7.exe
2020/03/01  01:28           102,754 pip2.exe
2020/03/01  01:29               428 rebot-script.py
2020/03/01  01:29            74,752 rebot.exe
2020/03/01  01:29               428 robot-script.py
2020/03/01  01:29            74,752 robot.exe

We can find robot.exe,can't find jbot,because it's alread combine to robot at Robot Framework 3.2b2,you can check it from Robot Framework Github for more.我们可以找到robot.exe,找不到jbot,因为它在Robot Framework 3.2b2中已经和robot结合了,你可以从Robot Framework Github查看更多。

All right,our env is done.好了,我们的环境就完成了。

check it!检查它!

**********SDK **********SDK

C:\Users\65787>jython --version

Jython 2.7.2b3

C:\Users\65787>java -version

java version "1.8.0_231"

Java(TM) SE Runtime Environment (build 1.8.0_231-b11)

Java HotSpot(TM) 64-Bit Server VM (build 25.231-b11, mixed mode)

C:\Users\65787>robot --version

Robot Framework 3.2b2 (Jython 2.7.2b3 on java1.8.0_231)

**********IDE: eclipse + red editor **********IDE:日食+红色编辑器

1.Download red editor from elipce markplace and install it. 1.从elipce markplace下载red editor并安装。

2.configuration robotframework in eclipce perfermance-->robotframework --->installe framework -> dicover (if does not work ,can manual cofig path at D:\\Tools\\jython2.7\\bin) 2.在eclipce perfermance中配置robotframework-->robotframework --->installe framework-> dicover(如果不行,可以手动配置路径在D:\\Tools\\jython2.7\\bin)

Lets's slove your problem.让我们解决你的问题。

===========prepar a java jar====================== ============准备一个java jar======================

0.prepar a jar or class/java file for robot framework! 0.为机器人框架准备一个jar或class/java文件!

this section I use a jar.这部分我用了一个罐子。

1.new a Maven project->robot-utils4j 1.新建一个Maven项目->robot-utils4j

2.new A HelloWorld class 2.new一个HelloWorld类

package org.mfm.robot.utils4j;

public class HelloWorld {
    public void hello(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public void doNothing() {
    }

}

2.pom.xml 2.pom.xml

<groupId>org.mfm</groupId>
    <artifactId>robot-utils4j</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>assembly</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

3.run mvn clean package 3.运行 mvn 清洁包

4.get a jar robot-utils4j-1.0.0-jar-with-dependencies from target directory. 4.从目标目录中获取一个jarrobot-utils4j-1.0.0-jar-with-dependencies。

=============run Robot with java jar================= ==============用java jar运行机器人==================

1.new a Robot project 1.新建一个机器人项目

2.import Library at red.xml 2.在red.xml中导入库

add new library in Refrenceed Library view.在参考库视图中添加新库。

click robot-utils4j-1.0.0-jar-with-dependencies library.单击 robots-utils4j-1.0.0-jar-with-dependencies 库。

search org.mfm.robot.utils4j.HelloWorld搜索org.mfm.robot.utils4j.HelloWorld

and click it并点击它

Finally ,The result will Like This:最后,结果会是这样:

enter image description here在此处输入图片说明

you'd better right click it mark as static libary.你最好右键单击它标记为静态库。

3.new a JavaHello.robot Test Suite 3.新增一个JavaHello.robot测试套件

JavaHello.robot JavaHello.robot

*** Settings ***   
Library    org.mfm.robot.utils4j.HelloWorld         

*** Test Cases ***
My Test
    Do Nothing
    Hello    world 

4.run it you will get this result: 4.运行它你会得到这样的结果:

Command: jython.exe -J-Dpython.path=D:\Tools\jython2.7\Lib\site-packages -J-cp .;D:\AllWorkspace\lib\robot-utils4j-1.0.0-jar-with-dependencies.jar;D:\AllWorkspace\lib\/*.jar -m robot.run --listener C:\Users\65787\AppData\Local\Temp\RobotTempDir8138272493583159262\TestRunnerAgent.py:14246 --argumentfile C:\Users\65787\AppData\Local\Temp\RobotTempDir8138272493583159262\args_2df9cc70.arg D:\AllWorkspace\EWorkspace4Java\RobotDemo
Suite Executor: Robot Framework 3.2b2 (Jython 2.7.2b3 on java1.8.0_231)
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
==============================================================================
RobotDemo                                                                     
==============================================================================
RobotDemo.JavaHello                                                           
==============================================================================
My Test                                                               | PASS |
------------------------------------------------------------------------------
RobotDemo.JavaHello                                                   | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
RobotDemo                                                             | PASS |
1 critical test, 1 passed, 0 failed
1 test total, 1 passed, 0 failed
==============================================================================
Output:  D:\AllWorkspace\EWorkspace4Java\RobotDemo\output.xml
Log:     D:\AllWorkspace\EWorkspace4Java\RobotDemo\log.html
Report:  D:\AllWorkspace\EWorkspace4Java\RobotDemo\report.html

Further more,I use redisson to connect a redis cluster in robot-utils4j-1.0.0-jar-with-dependencies.此外,我使用redisson连接robot-utils4j-1.0.0-jar-with-dependencies中的redis集群。

1.code 1.代码

The code of robot-utils4j: robots-utils4j 的代码:

package org.mfm.robot.utils4j;

import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

public class RedisClient {

        private static RedissonClient  instance = null; 

        /**
         * 获取连接redis的Session
         * @param clusterNodes "redis://127.0.0.1:7000", "redis://127.0.0.1:7001"
         * @param password abc123
         * @return
         */
        public RedissonClient getRedissonClient(String clusterNodes,String password) {
            Config config = new Config();
            config.useClusterServers()
                .setScanInterval(2000) 
                .setPassword(password)
                .addNodeAddress(clusterNodes.split(","));
            if(instance == null) {
                instance = Redisson.create(config);
            }
            return instance;
        }

        public static void main(String[] args) {
            RedisClient redisClient = new RedisClient();
            RedissonClient redissonClient = redisClient.getRedissonClient("redis://172.16.2.132:7001, redis://172.16.2.133:7002,redis://172.16.2.134:7003", "keplerredis");
            System.out.println(redissonClient+"连接成功。。。。");
        }

        public String getKey(String key) {
            RBucket<String> rvalue = instance.getBucket(key);
            System.out.println("获取key"+key+"的值"+rvalue.get());
            return rvalue.get();
        }

        public void setKeyValue(String key,String value) {
            RBucket<String> rvalue = instance.getBucket(key);
            System.out.println("获取key"+key+"的值"+rvalue.get());
            rvalue.set(value);
        }
}

2.import Library at red.xml 2.在red.xml中导入库

add new library in Refrenceed Library view.在参考库视图中添加新库。

click robot-utils4j-1.0.0-jar-with-dependencies library.单击 robots-utils4j-1.0.0-jar-with-dependencies 库。

search org.mfm.robot.utils4j.RedisClient搜索org.mfm.robot.utils4j.RedisClient

you'd better right click it mark as static libary.你最好右键单击它标记为静态库。

3.create Robot TestSutie 3.创建机器人TestSutie

*** Settings ***
Library    org.mfm.robot.utils4j.RedisClient  

*** Test Cases ***
My Test
    ${connectResult}=    Get Redisson Client    redis://172.16.2.132:7001, redis://172.16.2.133:7002,redis://172.16.2.134:7003    keplerredis
    Log To Console    ${connectResult} 
  1. Run it运行它

    ============================================================================== RobotDemo :: python.path ================================================== ============================ RobotDemo :: python.path
    ============================================================================== RobotDemo.RobotDemo ================================================== ============================ RobotDemo.RobotDemo
    ============================================================================== RobotDemo.RobotDemo.RedisDemoJava ================================================== ============================ RobotDemo.RobotDemo.RedisDemoJava
    ============================================================================== My Test org.redisson.Redisson@10bdfbcc | ================================================== ============================ 我的测试 org.redisson.Redisson@10bdfbcc | PASS |通行证 | ------------------------------------------------------------------------------ RobotDemo.RobotDemo.RedisDemoJava | -------------------------------------------------- ---------------------------- RobotDemo.RobotDemo.RedisDemoJava | PASS |通行证 | 1 critical test, 1 passed, 0 failed 1 test total, 1 passed, 0 failed ============================================================================== RobotDemo.RobotDemo | 1 次关键测试,1 次通过,0 次失败 总共 1 次测试,1 次通过,0 次失败 ================================ ============================================== RobotDemo.RobotDemo | PASS |通行证 | 1 critical test, 1 passed, 0 failed 1 test total, 1 passed, 0 failed ============================================================================== RobotDemo :: python.path | 1 次关键测试,1 次通过,0 次失败 总共 1 次测试,1 次通过,0 次失败 ================================ ============================================== RobotDemo :: python .path | PASS |通行证 | 1 critical test, 1 passed, 0 failed 1 test total, 1 passed, 0 failed ============================================================================== 1 次关键测试,1 次通过,0 次失败 总共 1 次测试,1 次通过,0 次失败 ================================ ==============================================

*************About *************关于

Library A图书馆A

Library A.java库A.java

Library A.class图书馆A.class

public class A{

    public void hello(String name) {
        System.out.println("Hello, " + name + "!");
    }

    public void doNothing() {
    }

}



*** Settings ***   
Library    A
#or Libary    A.java    this way is also ok 
#or Libary    A.class   this way is also ok 
#Both of these need javac A.java ,you need hava a A.class 

*** Test Cases ***
My Test
    Do Nothing
    Hello    world 

*************About robot commont and jython run with a Java or class file *************关于robot commont 和jython 用Java 或class 文件运行

At the same directory,you need to complier A.java同目录下需要编译A.java

javac A.java javac A.java

A.java

A.class

JavaHello.robot

run command运行命令

robot --pythonpath=. JavaHello.robot
#or
jython -Dpython.path=. -m robot.run JavaHello.robot
#or
jython -J-cp . -m robot.run JavaHello.robot

*************About robot commont and jython run with a jar *************关于robot commont 和jython run with a jar

jar-cvf my.jar A.class

get my.jar得到我的.jar

you can run it Use this commond, notice it你可以运行它使用这个commond,注意它

cd D:\AllWorkspace\EWorkspace4Java\RobotDemo\
D:
jython -J-cp D:\AllWorkspace\lib\my.jar -m robot.run JavaHello.robot

jython -Dpython.path=D:\AllWorkspace\lib\my.jar -m robot.run JavaHello.robot

jython -Dpython.path=D:\AllWorkspace\lib\/*.jar -m robot.run JavaHello.robot

or

robot --pythonpath=D:\AllWorkspace\lib\my.jar JavaHello.robot
robot --pythonpath=D:\AllWorkspace\lib\/*.jar JavaHello.robot

if you config CLASSPATH=D:\\AllWorkspace\\lib\\my.jar at window env "PATH"如果您在窗口环境“PATH”中配置 CLASSPATH=D:\\AllWorkspace\\lib\\my.jar

robot JavaHello.robot
jython  -m robot.run JavaHello.robot

About JYTHONPATH PYTHONPAHT CLASSPATH关于 JYTHONPATH PYTHONPAHT 类路径

You can get more info and diffrences from robot framework github doc.您可以从机器人框架 github 文档中获取更多信息和差异。

Ref: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#pythonpath-jythonpath-and-ironpythonpath参考: http : //robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#pythonpath-jythonpath-and-ironpythonpath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM