Previous Topic: Using BeanShell in DevTestNext Topic: Using Date Utilities


Using BeanShell Scripting Language

The major difference between BeanShell Java and compiled Java is in the type system. Java is strongly typed, but BeanShell can loosen the typing in its scripting environment. You can, however, impose strict typing in BeanShell if you want.

BeanShell relaxes typing in a natural way that lets you write BeanShell scripts that look like standard Java method code. However, you can also write scripts that look more like a traditional scripting language, such as Perl or JavaScript, while maintaining the Java syntax framework.

If a variable has been typed, then BeanShell honors and checks the type. If a variable is not typed, BeanShell only signals an error if you try to misuse the actual type of the variable.

The following Java fragments are all valid in BeanShell:

foo = "Foo";
four = (2+2) * 2 / 2.0;
print(foo + " = " + four);
.
.
hash = new Hashtable();
date = new Date();
hash.put("today", date);
.
.

BeanShell lets you declare and then use methods. Arguments and return types can also be loosely typed:

Typed

int addTwoNumbers(int a, int b){

return a + b;

}

Loosely Typed

add (a,b){

return a + b;

}

In the second example, the following works correctly:

sumI = add (5,7);
sumS = add("DevTest " , "Rocks");
sumM = add ("version ", 2);

BeanShell also provides a library of commands that facilitate its use.

A few examples of these commands are:

For more information, see the BeanShell User Guide at http://www.beanshell.org/.

You can also get BeanShell, the source code, and the complete Javadoc at the same place.

 

Using BeanShell as Stand-alone

BeanShell is available as a stand-alone interpreter so you can try it outside of DevTest. You can download BeanShell from www.beanshell.org. This download is a single small JAR file named bsh-xx.jar (xx is the version number; currently 2.0). Add the JAR file to your classpath.

You can use BeanShell in the following configurations:

 

Using BeanShell in DevTest

The BeanShell interpreter is used in the Java Script Execution step and the Assert by Script Execution assertion. Both of these elements also expose DevTest Java objects and the current DevTest state (properties). This provides a powerful environment for adding custom functionality. The exposed Java objects can be used to both interrogate and to modify the current state of the test. For example, you can read, modify, and create DevTest properties in your scripts.

As a starting point, become familiar with the TestExec class in DevTest. Information about TestExec and many other classes can be found in Using the SDK.

DevTest also uses BeanShell inside property notation when an equal sign is present. For example:

{{= new Date()}} 

This property expression is interpreted using BeanShell.