Tuesday, August 18, 2015

Parameterized integration tests with Spring JUnit Rules

Spring 4.2 comes with brand new JUnit rules: SpringClassRule and SpringMethodRule. The main advantage of using JUnit rules is to let developers get rid of SpringJUnit4ClassRunner and utilize different JUnit runners in Spring integration tests. I think the biggest opportunity with Spring JUnit Rules is the ease of creating parameterized integration tests.

Wednesday, July 1, 2015

Sahi Script Samples from my presentation at TrojQA

Sahi is an web automation tool that can be used to test modern web applications in a variety of browsers. Sahi comes in two flavors: open-source and commercial. Some of the key Sahi features include:

  • recording on most modern browsers - including Internet Explorer,
  • automatic AJAX waits
  • easy to learn and robust scripting - Sahi Script
  • built-in tools like reporting, logging etc.

This blog post contains some code snippets of Sahi Script that I presented during my talk at TrojQA in 2015. TrojQA is a Tricity (Poland) community focused on software testing and quality assurance.

If you are interested in learning more about Sahi, please visit its official website here: http://sahipro.com/.

Sahi Script

Sahi Script is a scripting language based on JavaScript. The main difference from JavaScript is that in Sahi Script variables must be prefixed with $.

_include("StringUtils.js")
var _system = (function () {
    var getenv = function ($name, $default) {
        var $env = java.lang.System.getenv($name);
        if ($env == null && $default) {
            return $default;
        }
        return $env;
    };
    var os = function () {
        var $os = java.lang.System.getProperty("os.name");
        return $os;
    };
    return {
        getenv: getenv,
        os: os
    }
})(); 

The snippet above creates a module that can be used in retrieving system properties (using Java code).

Sahi API

The power of Sahi Scripts is a Sahi API. Sahi API, among others, allows accessing elements on the browser and interact with them (Accessor API and Action API). To learn more about Sahi API please visit: http://sahipro.com/docs/sahi-apis/index.html.

Basics

Let’s have a look at a really basic script:

_navigateTo("http://themicon.co/theme/angle/v2.4/backend-angular/#/app/dashboard");
_assertEqual(1700, _getText(_div(0, _near(_div("Uploads")))));

The script is self exploratory and it instructs Sahi to do the following:

  • vavigate to a given URL
  • assert that the text in the first div that is located near div with the text Uploads is equal to 1700

Tables

While working with tables the Sahi API is really handy mostly due to well named methods and the relation API. The relation API allows matching elements that are related to each other. With tables this is extremely useful.


// find a table header with a given text
_highlight(_tableHeader("CSS grade"));

// find a table header with a given text within a concrete table
_highlight(_tableHeader("Platform(s)"), _in(_table("datatable1")));

// find a cell containing a text within a concrete table
_highlight(_cell("Gecko"), _in(_table("datatable1")));

// assert that table header's attribute is not empty
_assert(_tableHeader("Rendering engine").getAttribute("aria-sort") != "");

// compare text of the first row
_assertEqual("Gecko Firefox 1.0 Win 98+ / OSX.2+ 1.7 A", _getText(_row(1)));

// scrolling with JavaScript
_call(_div("Demo Table #2").scrollIntoView());

// fancy finding a checkbox within a table
_click(_span("fa fa-check", _near(_cell(/Holly Wallace/), _in(_table("table-ext-2")))));

Forms

Accessing and interacting with HTML form elements is


// click the link near a label containing a given text
_click(_link(0, _near(_label("Email:"))));
// set a value of email field
_setValue(_emailbox("Email:"), "john@doe.com");
// click submit button near email field
_click(_submit("btn btn-success btn-sm", _near(_emailbox("Email:"))));

// some other fields

_setValue(_telephonebox("Tel:"), "000-00-00");
_setValue(_numberbox("Number:"), "35");
_setValue(_rangebox("range"), "55");
_setValue(_urlbox("Url:"), "http://google.com");
_setValue(_datebox("Date:"), "2015-05-20");
_setValue(_timebox("Time:"), "01:00");

Page Object Pattern with Sahi Script

As Sahi Script can be easily modularized (_include) applying Page Object Pattern is possible. For small and medium project this should work pretty fine.

The Test Script:


// arrange
var $dashboardPage = new DashboardPage();

// act
$dashboardPage.navigateTo();

// verify statistics
_assert($dashboardPage.isAt());
_assertEqual(1700, $dashboardPage.statistics().uploads);
_assertEqual("700 GB", $dashboardPage.statistics().quota);
_assertEqual(500, $dashboardPage.statistics().reviews);
_assertEqual(70, $dashboardPage.statistics().averageMonthlyUploads);

The Page:

var DashboardPage = function () {

    var $_inboundVisitorStatistics = _div("Inbound visitor statistics");
    var $_inboundVisitorStatisticsCanvas = _canvas(0, _in(_div("panelChart9")));

    this.navigateTo = function () {
        _navigateTo($BASE_URL + "dashboard");
    };

    this.isAt = function () {
        return "Angle - Dashboard" == _title();
    };

    this.statistics = function () {

        var valueOf = function (name) {
            return _getText(_div(0, _near(_div(name))))
        };

        var getAverageMonthlyUploads = function () {
            return _canvas(0, _near(_div("Average Monthly Uploads"))).getAttribute("data-percentage");
        };

        return {
            uploads: valueOf("Uploads"),
            quota:   valueOf("Quota"),
            reviews: valueOf("Reviews"),
            // fits in statistics
            averageMonthlyUploads: getAverageMonthlyUploads()
        }
    };

    this.isInboundVisitorStatisticsVisible = function () {
        _log("Calling isInboundVisitorStatisticsVisible");
        return _isVisible($_inboundVisitorStatisticsCanvas);
    };

    this.collapseInboundVisitorStatistics = function () {
        if (!this.isInboundVisitorStatisticsVisible()) {
            _fail("Inbound visitor statistics are not visible. Can't collapse.");
        }
        _click(_link(0, _near($_inboundVisitorStatistics)));
        // let the panel collapse, 2nd argument must be a Sahi expression
        _wait(2000, !_isVisible($_inboundVisitorStatisticsCanvas));
    };

    this.expandInboundVisitorStatistics = function () {
        if (this.isInboundVisitorStatisticsVisible()) {
            _fail("Inbound visitor statistics are already visible. Can't expand.");
        }
        _click(_link(0, _near($_inboundVisitorStatistics)));
        // let the panel collapse, 2nd argument must be a Sahi expression
        _wait(2000, _isVisible($_inboundVisitorStatisticsCanvas));
    };

};

Source code

A full list of examples can be found here: https://github.com/kolorobot/sahi-script-samples

Running the scripts

  • Download and install Sahi OS
  • Download the scripts, unpack it and move to userdata/sahi-demo directory
  • Add sahi-demo to scripts.dir property in userdata/config/userdata.properties
  • Run Sahi Dashboard
  • Run a selected browser and open Sahi Controller
  • Switch to Playback tab and select sahi-demo script directory
  • Select a file, click Set and then Play

Tuesday, June 23, 2015

[Angular2]="{{'Hello, World!'}}"

As I mentioned in my recent blog post Angular 2 is a complete rewrite. Many concepts that are known from Angular 1.x are gone or changed dramatically. Angular 2 looks like a completely different framework: no DDO, no $scope, no angular.module and completely rewritten binding and change detection (no ng-model).

Although Angular 2 is still work in progress many new features have already been revealed. In this blog post I will share some basic concepts of the framework via code samples that I presented during my lecture at InfoShare 2015.

Please note the code is created with Angular 2 Alpha 26.

Angular 2 is built with… TypeScript (1.5)

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

We could say it is ECMAScript 6 on steroids, as it offers what ECMAScript 6 has to offer. But it adds many more features: type checking, interfaces, generics, enums or decorators to name just a few.

Let’s see some sample code created in TypeScript:

import {Greeter} from "greeter";

class HtmlGreeter implements Greeter {

    constructor(public greeting:string) {
    }

    greet() {
        return "<h1>" + this.greeting + "</h1>";
    }
}

var greeter = new HtmlGreeter("Hello, world!");
var greetings = greeter.greet();

TypeScript is optional for Angular 2 applications and although it is a recommended approach, developers have choice. They can choose from: ES5, ES6, CoffeScript or any other language that compiles to JavaScript.

Want to learn more about TypeScript? Visit http://www.typescriptlang.org/

Hello, World!

Let’s see two “Hello, World!” Angular 2 applications written in TypeScript and ECMAScript 5 accordingly.

TypeScript (1.5):

// TypeScript
import {Component, View, bootstrap} from 'angular2/angular2';

@Component({
    selector: 'hello-angular2'
})
@View({
    template: "<h1>Hello {{ name | lowercase }}</h1>"
})
class HelloAngular2Cmp {
    name:string = "Angular2";
}

bootstrap(HelloAngular2Cmp);

JavaScript (ES5):

// ES5
function HelloAngular2Cmp() {
    this.name = 'Angular2'
}

HelloAngular2Cmp.annotations = [
    new angular.ComponentAnnotation({
        selector: 'hello-angular2'
    }),
    new angular.ViewAnnotation({
        template: '<h1>Hello, {{ name }}!</h1>'
    })
];

document.addEventListener('DOMContentLoaded', function () {
    angular.bootstrap(HelloAngular2Cmp);
});

As you can see the TypeScript version is a bit less verbose and decorators (@) clearly separate the code from meta data information.

Angular 2 Building Blocks

As you could notice, the the above code did not contain much of what you learned about Angular 1.x: no angular.module, no Directive Definition Object (DDO), no $scope.

Component

A component is the main UI building block of Angular 2 app: Angular 2 is a tree of components. Every Angular 2 application must have at least one component. A component class is an execution context for the template or it is a component controller. A component requires a single @Component decorator and at least one @View decorator.

Let’s see a really basic component in Angular 2:

@Component({
    selector: 'hello-angular2'
})
@View({
    templateUrl: 'template.html',
    directives: [NgIf]
})
class HelloAngular2Cmp {

    private text:string;
    private clickCount:number = 0;

    onClick(input, $event) {
        this.text = input.value;
        if ($event instanceof MouseEvent) {
            this.clickCount++;
        }
    }
}

// let component be rendered on a page
bootstrap(HelloAngular2Cmp);

HelloAngular2Cmp has two properties: text and clickCount that are bound to a view defined by a template attribute of a @View decorator. Templates have access to any properties or functions of a component controller.

View

The template itself looks like this:


<!-- local variable input -->
<input type="text" #input>
<!-- event binding -->
<button (click)="onClick(input, $event)"
        [disabled]="text === 'Angular2'">Click me!</button>

<!-- property binding -->
<p>Angular2 says: {{ text }}</p>

<!-- Conditional -->
<div *ng-if="clickCount >= 5">Clicking too much, man!</div>

The syntax is very easy:

  • {{ expression | pipe }} - Angular 2 interpolation,
  • #variable – local variables available in the scope of the component. The variable can be later referred in the component’s template,
  • (event) - binding to events of element or directive,
  • [property] - binding to properties of element.

Bindings

Every time the text property of a component changes, the change is automatically reflected in the template. The properties of elements are accessed with square brackets ([property]) syntax. In the above example the button will be disabled once the text property of a component is equal to “Angular 2”. This is a property binding in Angular 2.

enter image description here

To propagate changes from DOM to a component event binding must be utilized. Event bindings in Angular 2 are represented by brackets syntax: (event). In the above example when a click event occurs on a button, onClick function of a component will be executed.

enter image description here

To sum up, in Angular 2:

Property bindings are executed automatically,
Event bindings allow propagation of DOM changes.

Watch this video to better understand the data binding in Angular 2: https://angularu.com/Video/2015sf/misko-hevery-talks-about-databinding-in-angular-2

Forms

Property and event bindings makes two two-way data binding possiblebut an additional effort is required in order to achieve it. Fortunately, Angular 2 will be shipped with Angular 2 Forms module. This module will be used for handling user input, by defining and building a control objects and mapping them onto the DOM. Control objects can then be used to read information from the form elements.

Read more about Angular 2 Forms: http://angularjs.blogspot.com/2015/03/forms-in-angular-2.html

Directive

A component is not the only UI building block in Angular 2. There are also directives which allow you to attach behavior to elements in the DOM.

The difference between a component and a directive in Angular 2 is that a component is a directive with a view whereas a directive is a decorator with no view.

A directive requires a single @Directive decorator and a directive class:

import {Directive, ElementRef} from 'angular2/angular2';

@Directive({
    selector: "[highlight]",
    hostListeners: {
        'mouseenter': 'onMouseEnter()',
        'mouseleave': 'onMouseLeave()'
    }
})
class Highlight {

    constructor(private element:ElementRef) {

    }

    onMouseEnter() {
        this.outline('#f00 solid 1px');
    }

    onMouseLeave() {
        this.outline();
    }

    private outline(outline:string = "") {
        this.element.domElement.style.outline = outline;
    }
}

The above directive, when used on an element, adds an outline effect to the host element – the element it is used on. ElementRef is automatically provided by Angular 2 Dependency Injection module.

Usage example:

<div highlight>Lorem ipsum...</div>

Dependency Injection

In Angular 2 there is a single way to inject dependencies into a directive or a component. In the below example a user-defined service is injected into a component. MessageService declares some business logic:

// messageService.ts
export class MessageService {

    private messages:Array<string> = [
        "Hello, Angular2",
        "Angular2 is cool!",
        "Damn it! Stop doing this!"];

    public getMessage() {
        return this.messages[Math.floor(
            Math.random() * this.messages.length)];
    }
}

The component is requesting framework to provide a required dependency via its constructor:

import {Component, View, bootstrap} from 'angular2/angular2';
import {MessageService} from 'messageService'

@Component({
    selector: 'hello-angular2'
})
@View({
    template: '<h1 (click)="onClick()">{{message}}</h1>',
})
class HelloAngular2Cmp {

    private message:string;

    constructor(private messageService:MessageService) {

    }

    onClick() {
        this.message = this.messageService.getMessage();
    }
}

The MessageService is imported from an external module and later it must be made available to Angular 2. One way to make dependencies available is to register them globally with a bootstrap() function like the one below:

bootstrap(HelloAngular2Cmp, [MessageService]);

Please note that framework services, directives or components, an iterable live list of components (@Query) and attributes (@Attribute) can be injected in the same, uniform way. The new DI module is designed the way it supports easy extending (DependencyAnnotation) so even custom dependency injection annotation can be created. In addition, Angular 2 supports injecting promises (@InjectPromise), lazy dependencies (@InjectLazy) or optional dependencies (@Optional).

Read more about Angular 2 Dependency Injection in this great article: http://blog.thoughtram.io/angular/2015/05/18/dependency-injection-in-angular-2.html

Summary

As you can see Angular 2 is much different from Angular 1.x. No DDO, no $scope, no angular.module, new change detection and binding, uniform template syntax, new dependency injection, new forms module, new router and much more.

The new version of the framework should also be much simpler to learn thanks to easier and more concise concepts like component-based architecture. Moreover, Angular 2 should be significantly faster than its ancestor thanks to completely rewritten data binding and change detection.

Is there a way to migrate from Angular 1.x? In my opinion it will not be easy. But there are some tips out there that may help in migration:

  • Prefer one-way data-bindings to two-way data-bindings,
  • Use ControllerAs syntax for easier migration to components,
  • Do not update application state inside watch functions,
  • Follow the newest releases (1.4, 1.5) and upgrade,
  • Think of using New Router when available (https://angular.github.io/router/),
  • Think of using TypeScript in Angular 1.x applications.

References

Monday, June 8, 2015

Angular 2: Hello, World! at InfoShare 2015

InfoShare is one of the biggest and the most attended Tech and New Media events in Poland. This year for the second time I have the pleasure to attend the conference as a speaker. I will be presenting at Tech Stage about Angular2, the successor of Angular 1.x.

Angular 1.x

Angular 1.x is the most popular Front-end framework these days. Last year we decided to adopt it in some of Goyello new projects. Today we have some experience to share. At the same time we are closely looking at the next generation of the framework.

Game changer

It is extremely easy to get started with Angular 1.x. It provides clear separation of presentation, data and application logic which is greatly appreciated especially by back-end developers as myself. Two-way data binding is one of the most appreciated features of the framework. The dependency injection makes it possible to modularize the code and test it in isolation. Directives are great way of creating reusable components and use them across the application with ease. As a result, people love and admire the framework since the very beginning.

All that glitters is not gold

There is no doubt Angular 1.x is a great framework. However it is incredibly difficult to master. The complex API and many concepts introduced since its launch make understanding the framework and thus using it effectively really hard.

Angular 1.x has started in 2009, so it is not so fresh anymore and it is criticized more and more, mostly for the features that made the framework so popular.

Two way data binding looks great at first sight, but it introduces coupling: everything can update everything. This makes debugging and tracking errors really difficult. In addition, the performance of the applications drops significantly with growing number of objects on the pages.

Directives are great, but have you tried to understand its API? How much time did you need to master directives? Restrict, isolating the scope, link (pre-link, post-link), compile, transclusion, directive communication (and more) makes developers really suffer.

The Angular team also noticed many issues with Angular 1.x. They decided to create the next version of the framework almost from scratch.

What’s new in Angular 2?

Angular 2 is built on top of modern web standards like Web Components or ECMAScript 6. Many of these standards are not yet natively supported by browsers but they can be used thanks to polyfills.

Angular 2 is a new opening: no controllers, no DDO, no $scope, no angular.module and no two-way data binding.

The new version of the framework should also be much simpler to learn thanks to easier and more concise concepts like component-based architecture. The built-in modularity will make it possible to create complex applications easier. Moreover, Angular 2 should be significantly faster than its ancestor thanks to completely rewritten data binding and change detection.

Angular 2 is work in progress but many concepts have already been shared. During my presentation entitled: “Angular 2: Hello, World!” I will show the basic concepts of Angular 2. Attendees will get an opportunity to see some bits of the code created with Angular 2 (developers preview).

Wednesday, May 27, 2015

Groovier Spring Boot Integration Testing

Recently I had a chance to use Groovy’s groovy.json.JsonSlurper in a soapUI REST project. The usage scenario in soapUI (in particular, soapUI Open Source) was very simple: in a Groovy assertion, load the content of a response into a variable and than verify it like this:

import groovy.json.JsonSlurper;

def slurper = new JsonSlurper()
def result = slurper.parseText(messageExchange.responseContent)

assert result.incidentType == 'Lorem ipsum'

This works well in soapUI. But what about Spring Boot integration tests? Can I make integration testing of REST API groovier?

Tuesday, April 21, 2015

JUnit: Testing Exceptions with Java 8 and AssertJ 3.0.0

AssertJ 3.0.0 release for Java 8 makes testing exceptions much easier than before. In one of my previous blog post I described how to utilize plain Java 8 to achieve this, but with AssertJ 3.0.0 much of the code I created may be removed.

Warning: this blog post contains mostly the code examples.

JAX-RS 2.x vs Spring MVC: Returning an XML representation of a list of objects

JSON is King as it goes to all kinds of REST* APIs, but still you may need to expose multiple representations, including XML. With both JAX-RS and Spring MVC this is very simple. Actually, the only thing to do is to annotate POJOs returned from the API call with JAXB annotation and that’s it.

But when it goes to serializing a list of objects, JAX-RS will do a bit better than Spring MVC, in my opinion. Let’s see.