Overview

Robot Framework Tutorial – Writing Keyword Libraries in Java

7 Comments

Robot Framework Tutorial

Part I: Robot Framework Tutorial – Overview
Part II: Robot Framework Tutorial – A complete example
Part III: Robot Framework IDE
Part IV: How to Structure a Scalable And Maintainable Acceptance Test Suite
Part V: Robot Framework Tutorial – Writing Keyword Libraries in Java
Part VI: Robot Framework Tutorial – Loops, Conditional Execution and more
Part VII: Robot Framework – Testing Windows Applications
Appendix A: Robot Framework – Compact Sheet

The new Robot Framework Tutorial 2016 series


In this series so far we have seen some high-level overview, and an example on how to start and implement a Robot Framework project from scratch beside some other topics. So now is time to write our first custom Keyword Library and we will do it in Java. Why in Java? The reason is simple: I do not know Python at all :-). But luckily Java is a quite popular language, thus this seems to be a viable choice anyway. Of course writing keywords in Java has some impact on the usage of the Robot Framework as explainded in the overview. It means Jython has to be used if any Test Library is written in Java, which might not always be desirable. Therefore we will cover the usage of the Robot Framework Remote Library in an follow-up article to this one as well. But first things first, let’s start with the pure Java Keyword Library …

Let’s start …

First look at a "complete" Test Library written in Java

First look at a "complete" Test Library written in Java

And we are finished :-). Ok, just kidding, but in deed is the above screenshot showing the complete Java code required for a working – but obviously incomplete – Keyword Library. To make things easy in this example we are testing the Java implementation of the Stack-Interface. Of course this does not make too much sense, but it helps focusing on what is needed to implement the library and not that much on some complicated test functionality. In addition this solution can then be nicely compared to the corresponding example used in this JBehave-Tutorial.

Writing a Keyword Library in Java just means to write one class in Java. All public methods of that class can then be used as keywords in the Robot Framework after importing the Library. To be able to use a Keyword Library written in Java in your Robot Tests it is easiest to create a JAR out of it.

Basically there is only one robot-framework-specific definition in this class, which is ROBOT_LIBRARY_SCOPE. For this just take a look at the below excerpt from the Robot Framework documentation:

Test libraries can control when new libraries are created with a class attribute ROBOT_LIBRARY_SCOPE . This attribute must be a string and it can have the following three values:

  • TEST CASE: A new instance is created for every test case. A possible suite setup and suite teardown share yet another instance. This is the default.
  • TEST SUITE: A new instance is created for every test suite. The lowest-level test suites, created from test case files and containing test cases, have instances of their own, and higher-level suites all get their own instances for their possible setups and teardowns.
  • GLOBAL: Only one instance is created during the whole test execution and it is shared by all test cases and test suites. Libraries created from modules are always global.

Of course in this one class implementing the keywords any others Java classes can be used as long as all needed libraries are bundled to the final JAR. One good example here could be testing for example some services of your application directly (e.g. performing Web-Service calls, etc.).

Development Environment & Project Sources

As can be already seen from the above screenshot I am using NetBeans for implementing the Test Library. That is just for the fun of it, as we are using Eclipse in almost all our projects. For implementing the Test Library that does not matter at all, as long as you are able to produce the JAR-file in the end. Just use your preferred development environment.

The sources of this example (including the NetBeans project files) are stored to GitHub as part of the Robot Framework Sample Project that has already been used here. Beside the Java-Sources and Project-Files the repository also contains an example how to take the Test Library into use in some Testsuite. All this will be shown in the course of this article.

Implementation and Usage

As already stated above, the implementation of the Test Library as such is not very complicated, especially as we have used a very trivial example here. It could of course get more complicated, but that has then nothing to do with this being a Test Library – as the approach always stay the same – but with a more complicated system to test.

The following shows the complete Java code required for the Test Library. It is compiled to a JAR-file and can thus be imported to any Testsuite or Resource File for usage.

package org.robot.sample.keywords;
 
import java.util.Stack;
 
/**
 * This is an example for a Keyword Library for the Robot Framework.
 * @author thomas.jaspers
 */
public class SampleKeywordLibrary {
 
    /** This means the same instance of this class is used throughout
     *  the lifecycle of a Robot Framework test execution.
     */
    public static final String ROBOT_LIBRARY_SCOPE = "GLOBAL";    
 
    //</editor-fold>
    /** The Functionality to be tested */
    private Stack<String> testStack;
 
    /**
     * Keyword-method to create an empty stack.
     */
    public void createAnEmptyStack() {
        testStack = new Stack<String>();
    }
 
 
    /**
     * Keyword-method to add an element to the stack.
     * @param element The element
     */
    public void addAnElement(String element) {
        testStack.push(element);
    }
 
    /**
     * Keyword-method to remove the last element from the stack.
     */
    public void removeLastElement() {
        testStack.pop();
    }
 
    /**
     * Keyword-method to search for an element position.
     * @param element The element
     * @param pos The expected position
     */
    public void elementShouldBeAtPosition(String element, int pos) 
            throws Exception {
        if (testStack.search(element) != pos) {
            throw new Exception("Wrong position: " + testStack.search(element));
        }
    }
 
    /**
     * Keyword-method to check the last element in the stack.
     * @param result Expected resulting element
     */
    public void theLastElementShouldBe(String result) throws Exception {
        String element = testStack.pop();
        if (!result.equals(element)) {
            throw new Exception("Wrong element: " + element);
        }
    }
}

So let’s see how we can import this library now into an example testsuite. Please note that we are using the very directory structure that was presented already in some previous article on a Robot Framework Example. It is shown here again for your quick reference.

Directory Structure

Thus our JAR-file belongs to the execution/lib-folder and our sample testsuite to the implementation/testsuites-folder.

Please note that there are already additional files located in those folder in the GitHub-project. But this is perfectly fine and the different examples can co-exist there without any problems.

Once we have stored the SampleLibrary.jar to the execution/lib-folder we can start implementing a sample testsuite in the implementation/testsuites-folder. Let’s call this one SampleLibraryTestsuite.html and do not confuse this one with the SampleTestsuite.html from the previous example ;-).

Importing our own SampleLibrary is not much different from importing any other keyword library. But as with every keyword library written in Java we have to give the full qualified package name of the corresponding Java Class in the import. Thus in RIDE this looks then as follows:

Importing the Sample Java Library

The rest of the implementation is then absolutely straight forward. The keywords can be used as any other keywords as well. The nice thing is that you do not have to use the precise method names, but you can vary upper- and lowercase and add spaces for better readability. Another screenshot illustrates this:

Basic Stack Test

Basically that is pretty much it. Of course we could very well use another startup-script to be able to easily start the tests. This one can be found from the example under execution/local/scripts as start_SampleLibrary_TestSuite.bat. It has the following content:

del ..\..\..\output\*.xml /Q
del ..\..\..\output\*.html /Q
del ..\..\..\output\*.png /Q

set CLASSPATH="..\..\lib\SampleLibrary.jar;%CLASSPATH%"
echo %CLASSPATH%

jybot --outputdir ..\..\..\output ..\..\..\implementation\testsuites\SampleLibraryTestsuite.html

The most important thing is for sure to extend the Java Classpath properly. To keep our example independent from where it is located (as folders might differ for different team members) we are using a relative path to locate the SampleLibrary.jar. As for sure we are now using at least one Java Library in our tests we have to use jybot (and thus Jython) to start the tests.

That is it! Your first keyword library is probably waiting already around the next corner :-).

In the next post in this series we will then see how to extend this Library to make use of the Robot Framework Remote Server Interface.

Thomas Jaspers

Long-term experience in agile software projects using
Java enterprise technologies. Interested in test automation tools and concepts.

Share on FacebookGoogle+Share on LinkedInTweet about this on TwitterShare on RedditDigg thisShare on StumbleUpon

Kommentare

  • Pekka Klärck

    Great tutorial again! Your Robot Framework tutorial series is awesome!

    There are two Java library related topics you might want to cover in some later posts:

    1) How to create library documentation for your Java libraries using libdoc [1]. This includes both HTML for humans and XML for RIDE. Nowadays when libdoc is bundled with the core framework using it is pretty simple.

    2) How to use JavalibCore [2]. This generic component eases creating larger Java based test libraries.

    [1] http://code.google.com/p/robotframework/wiki/LibraryDocumentationTool
    [2] https://github.com/robotframework/JavalibCore

  • Thomas Jaspers

    Hi Pekka,

    happy to hear you like it … I will try to cover those topics together with the Remote Interface, thanks for the hint. But it will take some time until the next post as I am rather busy right now and then the vacation time starts.

    Luckily I am not the only one @codecentric blogging on the Robot Framework … 🙂

    Best Regards
    – Thomas

  • Ruslan Platonov

    Thank you for the post, really helped me to start with Robot. As it’s a tool from Python world it was really difficult to find any good tutorial about how keywords written in Java can be used in Robot scenarios.

    To be hones I spent several hours just setting up a project in Eclipse that allows running scenarios from IDE. Recently I wrote a blog post about how to in a few minutes. I hope it may save a lot of time for someone who just starting.

  • Thomas Jaspers

    Thanks for your feedback and sharing your tutorial 🙂

  • Anup

    Hi
    I need a help.
    i am continuously trying to add a Java library to Ride but with no success.
    How can I add a spec file(xml) in the test suite to identify methods present in Java file ?

  • toni

    Hi, I’m getting this error all the time:
    Importing test library ‘org.robot.sample.keywords.SampleKeywordLibrary’ failed: ImportError: No module named org.robot.sample.keywords

    I’ve configured the spec file and and imported to ride. PYTHONPATH has the java file and xml (I also created a SampleKeywordLibrary.jar and SampleKeywordLibrary.class) but no matter what i do it gives the same error.
    Can anyone help?

  • Jack

    I open the sample project from RIDE. But RIDE can not load the java library, just load the google resource. I can not understand

Comment

Your email address will not be published. Required fields are marked *