How to use Enhanced FOR loops in Java

Hello everyone!

After today’s course connect at Sheridan College, I thought about writing this little piece on how we use the ENHANCED FOR LOOP in Java.

The feature was introduced in the Java SE 5 platform and makes it somewhat easier to iterate across Arrays and Java collections such as ArrayLists (or dynamic arrays). It is simple:

Screen Shot 2015-05-28 at 8.53.16 PM

In the enhanced loop, instead of declaring a variable to hold the index of the element and increase the index (using i++), you declare a variable to hold the element itself, so it must always be of the same type of the objects held in the array (or collection). There is no need to define when the loop is going to end, java goes all the way until the last element of the collection.

The colon in the syntax can be read as “in“, such as “for the dog in turn in the dogs array, do something”.

Lets see again how it works with the Java collection ArrayList.

Screen Shot 2015-05-28 at 9.13.07 PM

Hope this helps, keep in touch.

All the Best,


Smart Cities and IoT

Hello everyone.

I have recently read a lot of articles about the IoT, how hype it has become and many ways it could help people work out problems. According to Gatner’s Hype Cycle report for 2014, it has reached the peak of expectation for coming technologies.

Gartner's hype cycle 2014
Gartner’s hype cycle 2014

The Internet of Things is a concept that envolves the use of embedded computing devices connected to real objects, passing on information about them such as location, measures made by sensors, thus improving decision making by humans involved in the use of these objects.

Coming across the video below made me think about how the IoT and a Smart city would be connected. It happens that they are fully connected. On one side there is the data collection made by the embedded devices connected to different objects spread over the city, while on the other side there are the servers responsible for processing this data and make it available to the world via the Internet.

The concept involves M2M communication (Machine to Machine), without human intervention. It is not new the benefits brought about by this smart data treatment. For example, by using the world famous traffic mobile application Waze, you turn your mobile device into an object sending data to Waze’s servers, which then process the data and return to you the best way to avoid heavy traffic.



Protractor: Connect to MySQL

Hello everyone!

I’m back here to give you some extra tips on Software Testing using Protractor, this time how to connect to a MySQL database when testing your application at localhost.

Node.js is one of the coolest Javascript engines which provides tons of libraries to perform the most varied kinds of tasks. And should you need any task and do not have enough time to work around it using the native library, you may use the vast collection of 3rd party modules available at npm (Node Package Manager).

Today, we are going to connect to a MySQL database using the mysql library, developed by a bunch of developers and which has got only 140 206 downloads last month. Quite a lot don’t you think? And it works amazingly!

First, you will need to download the library running the following command from your testing root directory:

npm install mysql --save-dev

Remember, the flag


saves the reference to the module into your package.json file, so next time you install your testing system, you should only run:

npm install

And install all your dependencies at once.

Given the above, lets see how to organize the files to keep a modularised testing code. In my last post Protractor: The Page Object Model, I introduced an architectural model to keep your tests organised, and what we are going to need now is a PageObject.js, a testspec.js and a ConnectDatabase.js object.

In your PageObject.js, you are going to define attributes to store web elements and methods to perform actions on those attributes, for example addUser(callback). Please refer to Protractor: The Page Object Model for details.

Your ConnectDatabase.js will require the Node.js module mysql, define connection attributes to hold values and methods to perform actions.

function ConnectDatabase (){
var mysql = require('../../node_modules/mysql');

this.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'your_db_password',
database: 'your_db_name'
module.exports = ConnectDatabase;

Now imagine you wish to test if the creation of a user is really adding a new row into your users table in MySQL. You should better count the rows before adding the user and then after. Logically, the math is after = before + 1, and if it is not true, something is wrong.

After creating your connection object, which happens to be a function, you can use it within your testspec.js

//Require and instantiate the page object
var PageObject = require('../pageobjects/PageObject');
var pageObject = new PageObject();
//Database connection
var ConnectDatabase = require('../ConnectDatabase');
var connectDatabase = new ConnectDatabase();
var sql = 'SELECT COUNT(*) AS result FROM users_table';
it('Should add user and verify new entry in mysql', function() {
    //Defines variables to hold row count before and after addUser()
    var before;
    var after;
    connectDatabase.connection.query(sql, function(err, rows) {
        if (!err) {
            before = rows[0].result;
    //Inserts user and verifies row insertion
    pageObject.addUser(function() {
        //Counts rows after import
    connectDatabase.connection.query(sql, function(err, rows) {
            if (!err) {
                after = rows[0].result;
            //Tests rows after against rows before addUser()
        expect(after).toBe(before + 1);
}, 10000);

So that’s it guys, hope you enjoyed. Leave your comments, I’ll be glad to help you out. And remember, TESTING IS QUALITY!



Protractor: The Page Object Model

web element functions

This post aims at explaining a Test Automation design pattern I have com across during my work @ CESAR (Recife) writing software to execute E2E Test Automation. The Page Object Model applied to Protractor.

After conceptualizing different tools available for the job, the team opted for using a framework called Protractor [Github], which is an E2E Test Framework for Angular Apps, according to the project’s page

Developed to fit Angular Apps testing, it serves as a wrapper for Selenium Webdriver, providing advantages when compared to Selenium alone using Java. Apart from the element locators specific for Angular Apps, one of the main advantages is automatic waiting: it executes the next step of your tests as soon as the page finishes all pending tasks.

But the main purpose of this post is to provide you guys with a practical idea of designing an easily maintainable modularised auto-test suite based on the Page Object model. The tools used for the design of this suite were basically Node.js and Protractor, which wraps WebdriverJS and uses the Jasmine framework for BDD (Behavior Driven Development).

To design a maintainable, decoupled test automation solution, we should consider the same approach used for Java Page Objects. Each page should be encapsulated into their own object and instantiated at runtime. The directory structure destined to hold the Testware is the following. Notice we have used the same Java class notation, naming objects instantiated at runtime with Upper Case.

|---- protractor
   |---- configurationfile.js
   |---- package.json
   |---- data
      |---- set_one.js
      |---- set_two.js
      |---- dumpfile.sql
   |---- pageobjects
      |---- LoginPage.js
      |---- HomePage.js
   |---- connections
      |---- ConnectDatabase.js
      |---- ConnectAMQP.js
   |---- testconditions
      |---- Environment_one.js
      |---- Environment_two.js
   |---- tests
      |---- sanity.js
      |---- functional.js
      |---- feature_uat.js
   |---- node_modules
      |---- jasmine-reporters
      |---- mysql

We are going to use Node.js features to export Javascript objects as functions to the execution environment. For this reason, the design chosen was to define every object as an anonymous function. See below an example of the LoginPage.js.

var LoginPage = function() {
    //Constants - could be taken from a test DB for multilevel access test
    const URL = "http://localhost/login";
    const USERNAME = "roger";
    const PASSWORD = "1234";
    const LOGIN_OK = "Login Successful";

    //Attributes - WebElements of the page
    this.usernameElement = element("field_name_here"));
    this.passwordElement = element("field_id_here"));
    this.submitElement = element("field_id_here"));
    this.messageLabel = element("label_id_here"));

    //Methods - Actions performed at the page using the WebElements
    this.getLoginPage = function() {
    this.login = function() {

//This will export the module to Node.js runtime environment
module.exports = LoginPage;

At the test suite, you will invoke the Page Objects you will need to run you test, in this example a part of my sanity check, sanity.js.

//A page object required and Instantiated
var LoginPage = require("../pageobjects/LoginPage");
var loginPage = new LoginPage();

//The test suite and specs (it)
describe('Sanity Test Suite', function() {
    describe('Login test', function() {
        it('Should login and verify success', function() {
            loginPage.login().then(function() {
                loginPage.messageLabel.getText().then(function(text) {
        }, 10000);

Every element is a WebElement object, containing methods, such as click(), for example:;

If you create a method within the page object to print the object “this” to the terminal, you will be able to see all the elements mapped with their methods, for example:

Page Object:

this.printElements = function() {

Test file:


What you see is something like this (where passForm is the name of an attribute mapped to a WebElement):


All these functions you may use to perform many actions. They all return promises. For a more detailed look over the methods, please check the API.

For a great kick-off on how to use Protractor, checkout this Tutorial.



Node.js – Terminal colors (UNIX)

terminal with colors

Hello everyone!

Would you like to print out a fancy terminal log for your Node.js applications? Check this out…

Colourful Terminal

In this post I am going to tell you how to do it. This can be useful especially if you need to show WARNINGS, ERRORS or PASSING TESTS. In my case, I have a Queue Engine feature to test. The system under test must download files from the servers with or without the Queue Engine up and running, so I decided to print out WARNINGS in yellow should the Engine be not enabled and GREEN logs should everything be setup as expected. For this purpose, we would like to use ANSI escape sequences:

const TEXT = "\[\033[32m\] Your_text_here \[\033[m\]";

Okay, but what the hell are those numbers and characters all together? Well, this is BASH Scripting. Non printing escape sequences in BASH must be enclosed by:

\[\033[ <AND> \]

Although, when changing the color  of the output, the escape sequence must contain the character “m” before closing:

\[\033[ <AND> m\]

As you might have guessed, the number 32 on the first example represents the ANSI color code. So if you run:

const TEXT = "\[\033[32m\] Your_text_here";

You are going to print out in GREEN, but the problem is, it never returns to the regular color because there is no escaping sequence to tell the computer to do so! Okay, so lets try to place another escape sequence at the end to tell the machine to return to standard color output, then:

const TEXT = "\[\033[32m\] Your_text_here \[\033[m\]";

Looks pretty neat, but not so much. Why? Because this way you are telling the computer to only print this message in GREEN and then return to standard again. A nice way to deal with this, if you want to declare CONSTANTS with escaping sequences to print colorful texts in the terminal, you can use a PLACEHOLDER – represented by %s to print a STRING. Now, you would like to have this in your JavaScript code:

const MESSAGES = ["One message", "Another message"];
const GREEN = "\[\033[32m\] %s \[\033[m\]";

//Prints "One Message" in green
console.log(GREEN, MESSAGES[0]);

Okay, that is nice. But could get even better! You can send to the escaping sequence formatting, foreground color and background color, separated by semi-colons. For example:

const MESSAGES = ["One message", "Another message"];
const BOLD_RED_YELLOW = "\[\033[1;31;43m\] %s \[\033[m\]";

//Prints "Another Message" in bold (1) red (31) over yellow (43) background
console.log(BOLD_RED_YELLOW, MESSAGES[1]);

Now you’ve got cool colours and styles for your terminal debugging! Now take a look at the following link to find any colour you like…

ANSI escape sequences

Text attributes
0 - All attributes off
1 - Bold on
4 - Underscore (on monochrome display adapter only)
5 - Blink on
7 - Reverse video on
8 - Concealed on
Foreground colors
30 - Black
31 - Red
32 - Green
33 - Yellow
34 - Blue
35 - Magenta
36 - Cyan
37 - White
Background colors
40 - Black
41 - Red
42 - Green
43 - Yellow
44 - Blue
45 - Magenta
46 - Cyan
47 - White

Hope you like that, leave your comment!

Best, Raf.

%d bloggers like this: