information systems and computer engineering

76
Business Simulation Test Automation applied to Portuguese Social Security Hugo André Martins Rocha Thesis to obtain the Master of Science Degree in Information Systems and Computer Engineering Supervisor: Prof. José Manuel da Costa Alves Marques Examination Committee Chairperson: Prof. Mário Jorge Costa Gaspar da Silva Supervisor: Prof. José Manuel da Costa Alves Marques Member of the Committee: Prof. António Manuel Ferreira Rito da Silva May 2016

Upload: others

Post on 20-Dec-2021

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Information Systems and Computer Engineering

 

 

Business Simulation Test Automation applied to Portuguese Social Security

Hugo André Martins Rocha

Thesis to obtain the Master of Science Degree in

Information Systems and Computer Engineering

Supervisor: Prof. José Manuel da Costa Alves Marques

Examination Committee

Chairperson: Prof. Mário Jorge Costa Gaspar da Silva

Supervisor: Prof. José Manuel da Costa Alves Marques

Member of the Committee: Prof. António Manuel Ferreira Rito da Silva

May 2016

Page 2: Information Systems and Computer Engineering

 

 

Quality is not an act, it is a habit. Aristotle

Page 3: Information Systems and Computer Engineering

 

i  

Acknowledgments First, I would like to thank to my supervisor, Professor José Alves Marques for all granted help

and support in the course of this work. I would also like to thank to Professor Miguel Correia.

I warmly thank to my colleagues and co-workers: António Marques, Bruno Coutinho and Sara

Leal for their assistance throughout this work. Especially for their patience and support as testers

for the different solutions that were being developed until the final version.

Lastly, I am grateful to my family, to my beloved wife, Maria do Céu Rocha, to my son, André Rocha and

to my daughter, Raquel Rocha, as without them I would never achieve this goal.

Page 4: Information Systems and Computer Engineering

 

ii  

Abstract

Since many companies are doing test automation, you’d think it would be a simple task, but

there are challenges with incorporating test automation into your development cycle. Two of the

biggest challenges are the time and the skills needed to implement and maintain the test scripts.

Some organizations have started to look ahead for the ROI (Return of Investment) and stopped

doing automated tests, considering these difficult challenges.

This dissertation presents an innovative solution to address these challenges as it works like a

RAD (Rapid Application Development) model applied to the automated test scripts. As this

solution defines and generates a flexible class model easy to implement and change, it reduces the

effort of building and maintaining the test scripts. It uses BPMN (Business Process Model and

Notation) that document the functional specification of an application and from that graphical

diagram automatically generates all possible automated test scripts. Furthermore, it is also tool

independent if Java language is used.

Keywords

Test Automation, test scripts, Keyword-driven testing, BPMN, Test Cases, Use Cases

                    

Page 5: Information Systems and Computer Engineering

 

iii  

Resumo

Uma vez que muitas empresas têm adoptado a automação de testes, seria de pensar que esta se

revela como uma tarefa simples, mas existem vários desafios ao incorporarmos a automação de

testes no nosso ciclo de desenvolvimento. Dois dos maiores desafios são o tempo e as competências

técnicas necessárias para os implementar e manter. Algumas empresas ao perspectivar o futuro e,

consequentemente o ROI (Return of Investment), acabam por desistir da automação dos testes tendo

em consideração estes difíceis desafios.

Esta dissertação apresenta uma solução para endereçar estes desafios, tendo em conta que

funciona como um modelo RAD (Rapid Application Development) para implementar e manter os

testes automáticos. Uma vez que esta solução define e gera um modelo de classes flexível e fácil de

implementar e manter, reduz o esforço da construção e da manutenção dos scripts de teste. A

solução recorre a BPMN (Business Process Model and Notation) para documentar a especificação

funcional de uma aplicação e a partir dos diagramas gráficos são automaticamente gerados todos os

casos de testes possíveis. É também uma solução independente da ferramenta de automação usada,

no caso do recurso à linguagem Java.

Palavras Chave

Automação de Testes, scripts de teste, Testes baseados em palavras-chave, BPMN, Casos de

Teste, Casos de Uso

               

Page 6: Information Systems and Computer Engineering

 

iv  

Contents  

Introduction ....................................................................................... 1 

1.1  Motivation ...................................................................................... 2 

1.2  Goals and  Contributions ................................................................... 3 

1.3  Thesis Outline .................................................................................. 4 

State of the Art .................................................................................. 6 

2.1  How Automation Testing Tools Work ................................................ 7 

2.2  Automation Testing Tools on Portuguese Social Security .................... 8 

2.2.1  SilkTest ................................................................................................. 9 

2.2.2  Selenium .............................................................................................. 10 

2.2.3  TestAut ................................................................................................ 11 

2.2.4  Robot Framework .................................................................................. 13 

2.3  Using TestAut ................................................................................. 14 

2.4  Use Cases and Test Cases ................................................................ 15 

A New Approach for Test Automation ...................................... 18 

3.1  Architecture Overview .................................................................... 19 

3.2  Use Case Model to the BPM Model ................................................. 22 

3.3  Keyword‐driven Test Cases ............................................................. 25 

3.4  Automatic Generation of Keywords ................................................. 27 

3.5  Test Library and Factory Pattern ...................................................... 28 

Proof of Concept ............................................................................. 31 

4.1  Proof of Concept Overview ............................................................. 32 

4.2  Stage 1 – BPM Modeling ................................................................. 32 

4.3  Stage 2 – Generate the XPDL file ..................................................... 38 

4.4  Stage 3 – Generation of Test Scripts ................................................ 38 

4.5  Stage 4 – Implementing the Test Library using the Factory Pattern.... 39 

4.6  Stage 5 – Running the Test Scripts ................................................... 42 

4.7  Evaluating the Results ..................................................................... 44 

Conclusions and Future Work ..................................................... 45 

5.1  Conclusions .................................................................................... 46 

Page 7: Information Systems and Computer Engineering

 

v  

5.2  Future Work .................................................................................. 46 

Bibliography .................................................................................... 47 

Annex A – +Tester Screens .......................................................... A1 

Annex B – TestAut Screens .......................................................... B1 

Annex C – XPDL Parser source code .......................................... C1 

Annex D – Use Case & Business Rules real sample ............... D1 

 

Page 8: Information Systems and Computer Engineering

 

vi  

List of Figures and Tables 

Table 1 ‐ Requirements needed to improve Social Security test automation process. ........................ 11 Figure 1 ‐ TestAut Architecture. ............................................................................................................ 12 Figure 2 ‐ Application architecture. ....................................................................................................... 12 Figure 3 ‐ TestAut overview................................................................................................................... 14 Figure 4 ‐ Use Case example (complete Use Case on Annex D). ........................................................... 16 Figure 5 ‐ Business Rules example (complete set of Business Rules on Annex D). ............................... 17 Figure 6 ‐ Major steps sequence. .......................................................................................................... 21 Figure 7 ‐ Overview picture of the solution. ......................................................................................... 21 Figure 8 ‐ BPM Diagram example 1 (activities: tasks). .......................................................................... 24 Figure 9 ‐ BPM Diagram example 2 (gateways: exclusive). ................................................................... 24 Figure 10 ‐ BPM Diagram example 3 (events: start & termination). ..................................................... 24 Figure 11 ‐ BPM Diagram example 4 (groups). ...................................................................................... 25 Figure 12 ‐ BPM Diagram example 5 (events: link catch & link throw). ................................................ 25 Figure 13 ‐ XPDL example (activity unique identifier). .......................................................................... 27 Figure 14 ‐ Automatic generated test script example. .......................................................................... 28 Figure 15 ‐ Relation of the Java classes implemented in the solution. ................................................. 30 Figure 16 ‐ Mapping of Use Cases/Business Rules to Screens. ............................................................. 33 Figure 17 ‐ BPM diagram for Use Case (normal flow) – Annex D. ......................................................... 36 Figure 18 ‐ BPM diagram for complete Use Case ‐ Annex D. ................................................................ 37 Figure 19 ‐ Exporting XPDL file from bizagi. .......................................................................................... 38 Table 2 ‐ Comparison between current and new approaches .............................................................. 43 Table 3 ‐ Description of Manual and Automatic stages in this approach ............................................. 44  

Page 9: Information Systems and Computer Engineering

 

vii  

Abbreviations

API - Application Programming Interface BPM - Business Process Management BPMN – Business Process Model and Notation DB - Data base EE – Entidade Empregadora GUI - Graphical User Interface II – Instituto de Informática IP – Internet Protocol I.P. – Instituto Público JMS - Java Message Service JPA - Java Persistence API JRE - Java Runtime Environment OSD – Open Software Description PC – Personal Computer PDF – Portable Document Format QA - Quality Assurance QLF – Qualificação RAD - Rapid Application Development ROI - Return on investment SISS - Sistema de Informação da Segurança Social SQL - Structured Query Language SSD - Segurança Social Directa TestAut - Social Security Test Automation Framework UP - Unified Process URL – Uniform Resource Locator VBA – Visual Basic for Applications

Page 10: Information Systems and Computer Engineering

 

viii  

XLS – Microsoft Excel File Extension XML - Extensible Markup Language XPDL - XML Process Definition Language

Page 11: Information Systems and Computer Engineering

 

1  

                     Introduction

Contents

1.1 Motivation .............................................................................................................................................. 2

1.2 Goals and Contributions ........................................................................................................... 3

1.3 Thesis Outline ............................................................................................................................... 4

Page 12: Information Systems and Computer Engineering

 

2  

This chapter starts by presenting the main challenges in test automation, and then summarizes

the approach proposed in the dissertation. Finally, the chapter details the goals and contributions of

this work and the structure of the document.

1.1 Motivation

Over the past few years, several organizations with big and complex development cycles started

to implement test automation as part of their continuous integration process. These automation

tests are of particular importance and relevance to ensure that every daily build doesn’t “break”

and continues to work for the previous functionalities as it did, prior to the changes. This is called

regression testing [2].

Big software houses such as the Instituto de Informática, I.P. have complex and different software

architectures in order to implement solutions for its clients. One of its main clients is the Portuguese

Social Security, also known as Instituto da Segurança Social. Every year, more than 1300 new versions

are developed and tested from an overall of more than 100 applications. From these 1300 new

builds, 70% are related to maintenance versions and due to regression testing, which plays a very

important role here. Regression testing is massive and for that reason, investing in automating

regression tests is very important in this scenario. In addition, there are many data migration

projects which need data validation for millions of records. Automated tests, with pattern

matching, are fundamental for these migrations tests, since with manual testing only a very small

sample could be validated. For non-functional testing – and even for functional testing – big

volumes of data in the database are of extreme importance to test new applications. Test

automation can help achieving that goal. It is possible to implement test scripts that populate the

database of an application with the volume data needed [12].

In the last paragraph it is possible to understand that automation testing can play a very

important role in the following areas of the Portuguese Social Security:

a) Regression Testing

b) Volume Testing

c) Data Migration Testing

The process of implementing these automatic test scripts is done by means of an automation

testing tool that records the user actions, mouse clicks and keyboard inputs, and generates in the

end a test script, which can be played to execute the automatic test. It is also possible to create data

pools in order to be possible to use different data during the execution of these automation tests. In

Social Security the automation test tools used are: Selenium1, an open source tool, and SilkTest2, a

commercial tool from Micro Focus®. Both use Java3 language as the test script language. These tools

                                                            1 http://www.seleniumhq.org/ seen on 04/04/2016 2 http://www.borland.com/en‐GB/Products/Software‐Testing/Automated‐Testing/Silk‐Test seen on 04/04/2016 3 http://www.java.com/en/ seen on 20/04/2016 

Page 13: Information Systems and Computer Engineering

 

3  

and most of other automation test tools, individually, miss important features, like:

- A global and centralized repository for storing all the test scripts

- Control of test scripts versions

- Parameters in the scripts to use different test environments variables

- Detailed and centralized reports of the tests ran

- Schedule runs

- Possibility to run the tests in remote machines using a test farm of agents

- Utility libraries to support functionalities such as SQL queries on the database,

notifications by mail, screenshots and video recording

To overcome these missing features on automation testing tools, in general, a framework of

automation tests was implemented two years ago, using Selenium and SilkTest as the engines to

record and execute the scripts. This testing framework is called TestAut.

Nevertheless, even with this framework, implementing and maintaining automated test scripts

can be very time-consuming and skills-demanding. The development process used in Instituto de

Informática, I.P. is UP (Unified Process) and the analysis documentation is based on Use Cases and

Business Rules models. Defining the Test Cases and recording the test scripts is time consuming

and demands lots of concentration in order not to miss a particular test path or combination,

because text documents are being used.

This dissertation presents a new approach for implementing and maintaining automated test

scripts where the two previously referred as the “biggest problems” – time and skills – are no

longer valid reasons for not investing in the test automation area.

1.2 Goals and Contributions

This dissertation contributes by giving a step further into automation testing, expanding and

complementing the Portuguese Social Security automation testing framework (TestAut). It is based

on an approach followed by a former student in Link Consulting®, by means of keyword-driven

testing from BPM diagrams [20], which provides the capability of specifying the business processes

with a graphical notation [7, 15]. This will facilitate the perception of the processes since it is easier

to understand a graphic diagram than text specifications and will allow the implementation of a

parser that automatically generates the test scripts and, consequently, the Test Cases (since a test

script is the implementation of a Test Case).

The focus of the TestAut framework is test execution. This proposed solution, on the other

hand, focuses mainly in the early stages of the tests discipline activities by providing mechanisms

to design, implement and maintain the Test Cases and the test scripts in a more efficient way.

At the moment, the design of the Test Cases and the implementation of the test scripts is done in

the following way:

Page 14: Information Systems and Computer Engineering

 

4  

i) Reading and analyzing the Use Cases and Business Rules to design Test

Cases. Test Cases are designed manually and introduced into a custom tool,

developed by Instituto de Informática, I.P., called +Tester.

ii) Recording the Test Cases, designed in +Tester, with SilkTest or Selenium,

using the application under test.

This is a manual process that can lead to human errors, particularly in the design of Test Cases

in +Tester (one or more test paths or test conditions can be missed).

In this approach, tests were conducted to find the best solution to simplify and to accelerate

the process of test automation. As a result, the 3 main objectives of this dissertation were

established:

1- Define a conceptual approach to model the business through the use of the BPM

specification;

2- Build an architecture that will integrate with the test automation framework

(TestAut) that already exists, adding the necessary new components to expand

and improve this solution;

3- Do a proof of concept to test and evaluate this approach, by choosing a process (a

real Use Case and set of Business Rules) and implement the automated tests for

this process;

In the proof of concept, Use Cases and Business Rules are transformed into BPM (Business

Process Management) diagrams and test scripts are automatically generated for each path of that

diagram. The test scripts are written using reusable methods (keywords) corresponding to the

activities (tasks) in the diagram.

The main contributions of this work are: (1) a new approach to design Use Cases and Business

Rules using the BPMN diagrams; (2) automatically generate tests scripts with all possible scenarios,

from the BPM diagrams; (3) Automation Testing Tool independent if Java language is used.

1.3 Thesis Outline

Chapter 2 describes some existing methodologies related to test automation which are relevant

to this solution, as well as what differentiates them from this work. It also presents where Instituto de

Informática, I.P. is at the moment, regarding test automation and the evolution from here to this new

approach.

The approach is explained in Chapter 3, describing all the details from the functional

Page 15: Information Systems and Computer Engineering

 

5  

specification in the BPM model form to the automatic generation of all the test scripts.

The evaluation results are presented and discussed in Chapter 4.

Chapter 5 concludes the dissertation and discusses future work.

Page 16: Information Systems and Computer Engineering

 

6  

State of the Art 

                    

Contents 2.1 How Automation Testing Tools Work .............................................................................. 7

2.2 Automation Testing Tools on Portuguese Social Security ......................................... 8

2.3 Using TestAut ............................................................................................................................. 14

2.4 Use Cases and Test Cases ....................................................................................................... 15

Page 17: Information Systems and Computer Engineering

 

7  

 

2.1 How Automation Testing Tools Work

Manual testing is performed by a person sitting in front of a computer carefully executing the

test steps. Automation Testing means using an automation tool to execute your Test Case suite. The

automation software can also enter data into the system under test, compare expected and actual

results and generate test reports. By using a test automation tool it's possible to record this test suite

and replay it as required. Successive development cycles will require execution of same test suites

repeatedly. Once the test suite is automated, no human intervention is required. Nevertheless, Test

Automation demands considerable investments of money and resources [3, 5].

There are a lot of reasons as to why automated testing is beneficial and by using these best

practices in your automated testing, you can ensure that your testing is successful and you get the

maximum ROI. Thorough testing is crucial to the success of a software product. If your software

doesn’t work properly, chances are strong that most people won’t use it…or at least not for long. But

testing to find defects – or bugs – is time-consuming, expensive, often repetitive and subject to

human error. Automated testing, in which QA teams use software tools to run detailed, repetitive,

and data-intensive tests automatically, helps teams improve software quality and make the most of

their always-limited testing resources. Test Automation tools help teams test faster, allows them to

test substantially more code and improves test accuracy [4]. This is particularly important and

translates into much more benefits when used for automating regression testing, which would

require repetitive manual tests to be done over and over again, each time a new build of a particular

application is delivered for testing. If these regression tests were done manually an enormous

amount of time would be spent in these activities. Automating these repetitive tests will free up QA

engineers so they can focus on tests that require manual attention and their unique human skills.

First, and before you use a tool, you need to identify and define the Test Cases that you want to

automate. Second, you need to choose the right tool for your development environment and

architecture. Leaving important aspects aside, like price and support, and since these tools need to

be compatible with the GUI, the development language and technologies used to render the GUI

have an impact significance when choosing the right tool. For instance, if your GUI is in Java or

.NET4 you need to look for automate testing tools that work well with these technologies. If you are

using SAP maybe you will need a different tool and so on. After choosing two or three tools that are

compatible with your GUI environment, a proof of concept to choose the final one should be

considered for your final decision.

After the decision is made and the necessary knowledge was obtained to use the tool, the main

idea behind all of these tools is simple: you need to record (by using the application under testing

like a normal user) the Test Cases that you want to automate. Initially, the recording process seems

easy, but after the automated script has been generated you may need to do some adjustments. This

is where the challenge lies, and programmer knowledge is needed, so to speak. In fact, the scripts

                                                            4 https://www.microsoft.com/net/default.aspx seen on 20/04/2016 

Page 18: Information Systems and Computer Engineering

 

8  

are in a specific programming language: java, .NET or another programming language, depending

on the automation testing tool you are using. These adjustments can be done for several reasons: for

validations purposes (expected outcomes of the Test Case); to use different set of input data (for

example, using SQL to gather different data each time the script is executed); to make it compatible

with your application, if for some reason the recording process doesn’t work well; to expand and

make the test script more robust; and so on [6].

The engine behind these tools, when you are recording a test script, recognizes each object in the

GUI, by the type: combo box, text box, text area, radio button, table, etc. and by the name (the

internal name given to the object when it was programmed). Here, two problems can happen: (1) if

the name of the object was never defined or if it gets changed in a future build, the test script that

has the original name needs to be updated to reflect the new name; (2) if the tool engine doesn’t

recognize a particular object then it needs to use another method. This second method simply uses

a relative coordinate matrix (x, y) to identify an object within the GUI. So, if for some reason, an

object changes place, the test script will fail, since this object will not be found. This latter method

that these tools use in order to identify the GUI objects has far more pitfalls than the first one and

should only be used in last resort. In fact, to avoid the first problem, the QA team should inforce a

good practice so that the development team should always name the GUI objects and doesn’t

change their names.

Automation testing has proven not as easy as it may seem and it brings some challenges, but it

also has many advantages. So the real question is: Which Test Cases to automate [14, 17]?

a) Test Cases that are executed repeatedly (regression testing)

b) Test Cases that are very tedious or difficult to perform manually

c) Test Cases that are time-consuming

In the other hand, which Test Cases are not suitable for automation?

a) Test Cases that are newly designed and not executed manually at least once

b) Test Cases for which the requirements are often changing

c) Test Cases which are executed on ad-hoc basis

In fact, right selection of automation tool, testing process and team are important players for

automation to be successful. Manual and automation methods go hand-in-hand for successful

testing, as you can but shouldn’t automate every test [1].

2.2 Automation Testing Tools on Portuguese Social Security

 Since 1999, Instituto de Informática, I.P., has a dedicated QA team. From all those years, a long

road has been crossed and strategies and decisions were made regarding automation testing. This

Page 19: Information Systems and Computer Engineering

 

9  

company, for its main client, that is Portuguese Social Security, has developed more than 100

different applications within all these years. From all the development effort, 70% is maintenance,

because the requirements (Portuguese law and legislation) are always changing. As mentioned

before, Test Cases that are executed repeatedly, are the best candidates for automation testing. This

very high percentage value for maintenance builds led to a serious focus in test automation tools.

2.2.1 SilkTest  

In the past different sets of automation tools were used until, in the last 4 years, SilkTest started to

be used.

SilkTest is a commercial automation testing tool from Micro Focus®. It’s a robust and portable test

automation tool for web, native, and enterprise software applications. For web, SilkTest benefits of

cross browser testing feature, making it possible to test the different typical browsers: Internet

Explorer5, Firefox6 and Chrome7, with a single, portable test script. It supports different interfaces:

from IDE (in Java or .NET, for testers with programmer skills) to visual and graphical interface, for

testers with no programmer skills. It supports Visual Studio8 and Eclipse9 IDEs and it is easy to

integrate with unit testing, like jUnit for Java. This tool is also used in unit testing, for early testing:

Each time a new build is compiled, a set of regression tests in JUnit from SilkTest are run to make sure

the new build doesn’t break and it is ready for System Testing.

SilkTest works across a wide variety of technologies, from ‘legacy’ to the latest web applications. In

this way it is possible to carry out our test automation without the need to invest in different products

for diverse technologies, which eliminates the need for additional learning and money. Because II, I.P.

develops applications in different architectures like: Java GUI fat client, SAP10, web based, BPM, .NET,

this cross platform compatibility feature between different kinds of architectures / technologies and

browsers, is of most importance. Even for mobile applications, where II, I.P. is now giving the firsts

steps in developing new apps, SilkTest also supports this platform. The object to interact with can be

located and a specific execution command can be assigned to it. There are common commands such as

'click', and type-keys, that work in all supported technologies and there are also technology-specific

commands like pressing the home-button on a mobile device. In the present, II, I.P. has more than 30

applications, mainly with Java GUI interface, with automate test scripts from this tool, in a total of

around 500 scripts.

                                                            5 http://windows.microsoft.com/pt‐pt/internet‐explorer/download‐ie seen on 10/04/2016 6 https://www.mozilla.org/pt‐PT/firefox/new/ seen on 10/04/2016 7 https://www.google.com/chrome/ seen on 10/04/2016 8 https://www.visualstudio.com/ seen on 20/04/2016 9 https://eclipse.org/ seen on 20/04/2016 10 http://go.sap.com/index.html seen on 20/04/2016 

Page 20: Information Systems and Computer Engineering

 

10  

2.2.2 Selenium

Two years ago, II, I.P. started to develop a new architecture called “Visão 2.0”, a web-based

architecture. Even though SilkTest supports web clients, Selenium [10] is an open source

automations testing tool specific for the web platform. It is a plugin for Firefox and has the support of

some of the largest browser vendors who have taken (and are still taking) steps to make Selenium a

native part of their browser. It is also the core technology in countless other browser automation tools,

APIs and frameworks. Selenium uses a technology called WebDriver. It is an API for driving natively

a browser, and the main browsers like Firefox, Chrome and Internet Explorer, are supporting this

technology. Different benchmarks with SilkTest versus Selenium were done, in order to choose, from

this two, the best one for automating tests in web environments. The main advantages using

Selenium over SilkTest, are:

1- Selenium has bigger and better support for browsers because of the WebDriver

technology being already a part of the main browsers development like: Firefox, Chrome

and Internet Explorer. This is a standard with these browsers which makes Selenium

much more compatible with the web applications under test that uses these web clients. It

is also a fact that by using both tools with different web applications and SilkTest had

compatibly problems identifying some GUI objects that Selenium didn’t, whilst the

opposite didn’t happen.

2- Selenium doesn’t need the focus on Windows to execute the automate tests. The browser

can be minimized while the test scripts are running in the background and the tester can

be doing other tasks on the PC. In contrast, SilkTest needs the focus to properly run the

test scripts. If the user changes the mouse focus, SilkTest will fail the tests instantly. So,

when SilkTest scripts are running the tester can’t perform another action on his PC and

needs to wait until the tests are done.

3- Selenium is a lot faster than SilkTest on executing the test scripts (with same Test Cases)

in all the benchmark comparisons with different web applications that were done.

4- Selenium is an open source project and supported by a vast community. It is already a

standard for automation tests in the web. SilkTest, it’s a commercial product, meaning

that it’s not free. Besides the price, in the past, another commercial tool was used before

SilkTest, called TestPartner11 from Compuware®. For this tool, is built around it, a

framework to easily implement the test scripts. So instead of looking and dealing with

VBA language for customizing and maintaining the scripts, all the test scripts could be

                                                            11 https://en.wikipedia.org/wiki/TestPartner seen on 04/04/2016 

Page 21: Information Systems and Computer Engineering

 

11  

done in an Excel spreadsheet. Each sheet represents a screen, each column a GUI object

and each row an input / behavior for the GUI object. A lot of work and time were

invested to implement this framework with TestPartner and implemented near a

thousand of scripts for this tool. Some years later, Compuware® QA tools were sold to

Micro Focus®. Afterwards, Micro Focus® announced that TestPartner was discontinued. All

these to say that commercial tools have more risk being discontinued than successful open

source projects like Selenium.

Summing up, Selenium in the web realm, is more compatible, more productive, faster, less

expensive (free) and not as prone to be discontinued in the future, in comparison with SilkTest. That’s

why it was chosen for automation testing on the web. On the other hand, SilkTest has wider platform

support. That’s why it is used, especially for automation testing on fat client architectures, legacy

systems and SAP applications.

2.2.3 TestAut

After using other tools in the past, and lately these ones as stand-alone “solutions” for

automation testing, some challenges were faced that these testing tools by their own could not give

all the answers. To face these challenges, the following requirements were identified as being

necessary (see table 1).

Table 1 ‐ Requirements needed to improve Social Security test automation process 

1 A global and centralized repository for storing all the test scripts

2 Control of test scripts versions vs application under test

3 Parameters in the scripts to use different test environments variables

4 Detailed and centralized reports of the tests executions

5 Schedule executions

6 Possibility to run the tests in remote machines and in parallel, using a

test farm, freeing up the PC where the testers work

7 Execute SQL queries to obtain test data and validate test results

8 Define different user profiles for script maintenance

9 Test scripts templates

10 Re-use of code in different test scripts

11 Incorporating different automation testing tools in the test farm, such

as SilkTest and Selenium

Two years ago, a particular automation testing framework called TestAut began to be

developed and it is being used since September 2015, in Instituto de Informática, I.P.

It is important to clarify that the TestAut framework doesn’t’ replace automation testing tools.

Page 22: Information Systems and Computer Engineering

 

12  

These tools are still needed to record the test scripts and play them. In fact, they are a part of this

testing automaton framework.

In the figure 2, TestAut system high level architecture is presented. This framework is

composed by 3 main parts: TestAut server (TestAutEAR), TestAut clients (AgentTestAut#n) and

TestAut database (TestAutDB).

 

 

 

 

 

 

 

 

 Figure 1 ‐ TestAut Architecture.

The technologies used to implement this solution, as shown on figure 3, were:

- Server side developed in Java and running in Glassfish Appserver 4.0

- Client (agent) developed in Java and running on JRE 1.7

- Communication between agent and server using webservices

- Scheduling processes implementation using JMS

- Persistence of data using JPA

- Oracle 11g as the database to store all the data

- Web interface for the Framework GUI

- Robot Framework used for the integration between the agent and the test

automation tool (SilkTest and Selenium)

 

 

            

Figure 2 ‐ Application architecture.

DB

Glassfish

WebSite

WebServices

JMSJPA

Spring WebBroser

Soap Client

Agent

EJB

Page 23: Information Systems and Computer Engineering

 

13  

TestAut was implemented based on those 11 requirements shown in the previous table 1, but it

was also extended further with more features, such as:

- Concept of Test Suite: a set of test scripts with automation tool independence.

Scripts can either be from SilkTest, Selenium or from a combination of both;

- Test Suite executions history

- User experience: Possibility to define checkpoints in the scripts to measure response

times

- Extended Library (TestAutLib): API with more advanced features to incorporate in

the test scripts: capture of screenshots, handling of exceptions, error logging, etc.

- Live video: during an execution in an agent machine, video streaming can be

activated in real time to see what is happening in that execution machine

2.2.4 Robot Framework

Robot Framework12 is a generic test automation framework. It has easy-to-use tabular test data

syntax and it utilizes the keyword-driven testing approach. Its testing capabilities can be extended by

test libraries implemented either with Python or Java, and users can create new higher-level

keywords from existing ones using the same syntax that is used for creating Test Cases. Robot

Framework is part of the TestAut solution. It is used on the agents, responsible for executing the test

scripts. These test scripts are junit type exported from SilkTest and Selenium tools. Each test script

is implemented with reusable keyword on the Robot Framework. The reports from the test

executions are generated by using the Robot Framework reports feature. The main role of the Robot

Framework in TestAut solution is for the integration part between the agent and the test automation

tool in use: SilkTest or Selenium and by controlling and executing the test scripts, within a suite,

where each test script is a keyword on the Robot Framework [16].

 

 

 

 

 

 

 

 

 

 

                                                            12 http://robotframework.org/ seen on 14/04/2016 

Page 24: Information Systems and Computer Engineering

 

14  

2.3 Using TestAut  

So how to use TestAut solution? Figure 4 gives a general overview, identifying the main

components of this Automation Testing Framework.

 

 

 

 

 

 

 

    

 

 

Figure 3 ‐ TestAut overview.

Before starting to record scripts in SilkTest or Selenium, to automate Test Cases for a particular

application, first Test Cases need to be written. A custom solution was also developed, for test

planning, test design, manual testing executing and reporting, called +Tester (screenshots on Annex

A). This is where it is designed manually the Test Cases based on the application requirements: Use

Cases and Business Rules.

After having the Test Cases, that are needed to automate tests on a specific application, the main

steps to use TestAut framework are, as follow:

1- Record the test scripts, based on the Test Cases designed in +Tester, in one or both tools:

SilkTest and Selenium;

2- Incorporate the Java test scripts generated by these tools in the TestAut template

(requirement 9 from table 1) to use the API of TestAutLib;

3- Login in TestAut with proper user profile for inserting and editing test scripts

(requirement 8 from table 1);

4- Upload the test scripts to TestAut using the web interface, choosing the area of the

project and the application under the area related to those scripts (requirements 1 and 2

from table 1);

5- Associate these test scripts to test cases and the test cases to a test suite. Only a test suite

can be executed in TestAut (requirement 11 from table 1);

6- Edit the test scripts within TestAut to use different input data, like data pools, that can

Page 25: Information Systems and Computer Engineering

 

15  

be obtain in runtime by executing SQL queries to fetch these data and to also validate the

test results (requirement 7 from table 1);

7- Edit the test suite to use the target environment through the means of URL, IP address,

data source, and other custom variables needed to specify all the test environment

variables (requirement 3 from table 1);

8- Schedule the runs and choosing the agent in a remote machine, from a test farm, where

the execution will run (requirements 5 and 6 from table 1);

9- After the agent completes the execution of the test suite, look at the general and detailed

reports produced (requirement 4 from table 1);

Note: the same test script can be used in different test suites, and in each instance of that test

script, different test script variables and different test suite settings can be used. This feature fulfils

requirement 10 from table 1. In Annex B there are some screenshots of this tool.

2.4 Use Cases and Test Cases

Instituto de Informática, I.P., has adopted many years ago, the UP model for the development

cycle of applications. One of the main characteristics of this model is the Use Cases artifacts that

describe the functionality of an application. These artifacts, combined with the Business Rules

document are the main input for designing the Test Cases which can be either manual or automatic

tests. To derive Test Cases from Use Cases and Business Rules, one’s need to cover the different

paths of the main flow and alternative flows from the Use Cases (see sample example on figure 5)

and combine that with the different validations of the Business Rules (see sample example on figure

6). Since all are text documents, the design task of Test Cases is more difficult and more prone to

human errors. Besides, if Test Cases are to be automated, they need also to be mapped to the

different screens of the application under test.

In chapters 3 and 4 of this dissertation, a real Use Case and set of Business Rules are used, for a

Portuguese Social Security application, called QLF, developed by Instituto de Informática, I.P. The

Use Case name is: UC_001 – Consultar qualificações de trabalhadores de EE. It has a normal flow

with 9 steps and 26 alternate flows (in average each alternate flow has 3 steps). Moreover, the Use

Case calls 11 different Business Rules. In total there are 11 full A4 pages describing this

functionality. The Test Cases were previously, some months ago, designed manually in +Tester,

with current methodology. In this tool, a feature to measure the time spent for designing the Test

Cases and for manually executing them, was implemented. It took us 2 days for producing 57 Test

Cases. Comparing the number of Test Cases designed manually versus the new approach in this

dissertation, 15 Test Cases scenarios were missed (combinations between flows and Business

Rules). Nonetheless, it is easy to understand that manually designing Test Cases is a very time-

consuming and prone to human errors task. Chapter 4 will present the results from this new

approach.

Page 26: Information Systems and Computer Engineering

 

16  

                                      

Figure 4 ‐ Use Case example (complete Use Case on Annex D).

   

Page 27: Information Systems and Computer Engineering

 

17  

 

Figure 5 ‐ Business Rules example (complete set of Business Rules on Annex D).

Page 28: Information Systems and Computer Engineering

 

18  

A New Approach for Test Automation        

Contents 3.1 Architecture Overview .............................................................................................................. 19

3.2 Use Case Model to the BPM Model ...................................................................................... 22

3.3 Keyword Driven Test Cases ................................................................................................... 25

3.4 Automatic Generation of Keywords .................................................................................... 27

3.5 Test Library and Factory Pattern ....................................................................................... 28

Page 29: Information Systems and Computer Engineering

 

19  

 

3.1 Architecture Overview

The architecture proposed addresses the several activities involved in the test discipline, from

test planning to test execution. This solution was built from scratch, in terms of methodology and

processes implementation. Its main goal is to improve the efficiency and the quality of the testers

work. In order to do that, a new methodology based on the BPM modeling is proposed which

involves the following steps:

1 – Representation of the Use Cases and the Business Rules in BPM.

At the moment, the test cases are designed manually by following each of the flows in the Use

Cases and identifying, for each flow, the test conditions and the test results (pre-conditions and

post-conditions). The Test Cases are then the combination of all of these test conditions. In this way,

the Test Cases design can take a long time and it’s easy to miss an important combination.

In this new methodology, the Use Case is represented in a BPM diagram where each flow is

modeled using activities and gateways. The activities represent all the actions and the gateways all

the decisions. Each path in the diagram will represent a Test Case which results in a much simpler

way of extracting the Test Cases, automatically, without human interaction.

2 - Running a XPDL Parser that automatically generates the test scripts for all the paths and

the Test Library with all the keywords.

Having the BPM diagram designed, it is thus possible to export the diagram to a XPDL file [19].

This is a XML document that is part of the BPM specification which represents the BPM diagram

where each element (activity, gateway or transition) is identified by a unique id. Since each id is

unique (for example, e5ade915‐6533‐4fee‐b1bf‐6702782dac1f), it can be used as a keyword in the test

scripts to identify the activities. This way, the keywords can then be transformed to Java methods to

be executed by the test scripts.

Because Java has defined rules to the names of the methods, this id is modified in the following

way by the parser:

- It appends the “activity_” string at the beginning (Java methods can’t start with

numbers and since the id is a hexadecimal string it can happen);

- The “-“ is transformed in “_”

As a result, the id e5ade915‐6533‐4fee‐b1bf‐6702782dac1f will be modified to the Java method

activity_e5ade915_6533_4fee_b1bf_6702782dac1f(). Given this XPDL file, it’s easy for the parser to

generate the test scripts. Since a valid path in the diagram represents a flow to be tested, a test script

is generated by the parser for each path in the diagram. This is done in the following way:

- Following the transitions in the diagram, respecting the gateway conditions, to generate a list

Page 30: Information Systems and Computer Engineering

 

20  

of activities to be executed for each path;

- For each activity, generate a Java method in the Test Library;

- Combine the activities for each path and generate the test scripts using the Java methods of the

Test Library;

The outcome will be the following:

- The several test scripts that calls the Java methods corresponding to the keywords

(ids of the activities) which are implemented in the Test Library;

- The Test Library that contains the implementation of the Java methods referenced

in the test scripts. Doing this, each Java method (keyword) needs to be implemented

only once for all the test scripts, which is a great advantage in this solution. For

example, the login is an activity that is present in all the paths. If this Test Library

didn’t exist, it was necessary to implement it in all the test scripts.

3 - Implementing the generated keywords in a Test Library through the use of a Tool Factory

and a project Common Lib. The Tool Factory gives automation tool independence and the project

Common Lib contains all the shared objects;

4 - Executing the generated test scripts in the TestAut framework which provides several

features such as scheduling, results reporting, central repository, version control, different

automation tools to run, mail notifications and many others extra features;

In the following figures, figure 7 is a sequence diagram of the major steps of the solution,

showing the main activities involved in each one. Figure 8 is the overview picture of the global

approach. It represents the components and their relations.

Page 31: Information Systems and Computer Engineering

 

21  

 

                  Figure 6 ‐ Major steps sequence. 

                                                               

                     Figure 7 ‐ Overview picture of the solution. 

                  

Page 32: Information Systems and Computer Engineering

 

22  

3.2 Use Case Model to the BPM Model

The first step of this solution - and the first important part - is to translate Use Cases, Business

Rules and Storyboards to BPM diagrams. These diagrams must reflect the way the application

works. However, Use Cases only contain the business specification, they do not reflect the

application screens and the way the developer implements the business rules. The matching

between Business Rules and the application screens still needs to be done. For example, to access an

operation the login must be done first, but the Use Case for that operation does not reflect this pre-

requisite. It only cares about what the operation should do, not how it should be done.

A Use Case consists of a set of flows which are divided into steps. Each step can also reference

Business Rules. These Business Rules contain validations, calculations or other kind of algorithms.

The main flow is called the normal flow, which is the best case scenario that the main actor,

(habitually a user) will do. From this main flow it is possible to go to the alternative flows. On

previous figure 5 there is an example of a Use Case and in figure 6 a set of Business Rules example.

Both are used later in the proof of concept (chapter 4) of this dissertation [18].

The transformation of a Use Case to a BPM diagram is done in the following way (Annex D has

the complete Use Case and Business Rules used in this explanation):

- Start in step one of the normal flow and identify all the test conditions for all the

steps of the flow. When the normal flow is covered, the test conditions of the

alternative flows should be identified;

- For each of these test conditions, identify what happens when they are true

(actions);

- Map each of these test conditions to the application screens;

- Start building the BPM diagram following the order of the screens, identified on the

Storyboards, and doing the following:

o The actions extracted from the Use Case and the application screens are

mapped to activities (figure 8)

o The identified test conditions and the application decisions are mapped to

exclusive gateways (figure 9).

The example in this picture shows an exclusive gateway with 3

conditions (an employer with more than 50 workers; with less than

50 workers and with no workers). This gateway is necessary

because the application behaves differently in each case. To export

the files for an employer with more than 50 workers, the user has to

Page 33: Information Systems and Computer Engineering

 

23  

choose the type of the file (PDF, XLS or ODS) from a combo box

and the file will be sent by mail. If the employer has less than 50

workers, the user clicks the search button, sees the results in a grid,

selects the file type and saves the file to the disk. If the employer

has no workers, the option to export the file does not appear.

o Group the elements of the diagram according to the Use Case flows (figure

11). This picture shows the representation of the alternative flow 2A. If, for

some reason, something changes in the Use Case, it is easy to see where the

diagram needs to be altered since there is a visual association.

o Represent the jump of the normal flow to the alternative flows by link

events (figure 12). There are two reasons for this choice: first, to simplify the

diagram with fewer lines turning it more clear and readable. The second

reason is to make an analogy with the methodology of flows identification

in UP. For instance, in a test scenario that initiates in step 1 of the normal

flow and then continues step by step until step 5 where it “jumps” to

alternative flow 5A, with a UP methodology it becomes represented in the

following way:

1.Normal.5- > 5A where “- >” represents a jump in the flow. The link events

try to reflect this approach.

- The rules of the BPMN must be followed:

o The BPM diagram must have the start and termination events (figure 10)

o An exclusive gateway can’t have more than an entry. If more than one

transition must be connected to the gateway, it is necessary to use an

auxiliary non-conditional gateway (figure 9);

o A condition associated to an exclusive gateway cannot be connected to

more than one activity. In this case it is also necessary to use an auxiliary

non-conditional gateway (figure 9)

        

Page 34: Information Systems and Computer Engineering

 

24  

               

Figure 8 ‐ BPM Diagram example 1 (activities: tasks). 

              ~ 

Figure 9 ‐ BPM Diagram example 2 (gateways: exclusive). 

 

              

Figure 10 ‐ BPM Diagram example 3 (events: start & termination). 

 

Page 35: Information Systems and Computer Engineering

 

25  

   

 

  

 

    

Figure 11 ‐ BPM Diagram example 4 (groups). 

                

Figure 12 ‐ BPM Diagram example 5 (events: link catch & link throw). 

3.3 Keyword-driven Test Cases

Technically speaking, keywords are the basic and reusable building blocks for keyword test

design. Keywords define actions that drive or get information from application objects. Keywords

are defined with an action-descriptive keyword name (e.g. Hotel Reservation System Start, Hotel

Reservation Enter, Hotel Select, Reservation Confirmation Validate, or Hotel Reservation Close)

and keyword argument names (e.g. Country, City, CheckinDate, CheckoutDate). For GUI applications

each keyword is associated with one (or sometimes more) GUI windows. Each keyword argument

may be associated with a window object, like a list-box or a button. Reuse of Keywords ensures

rapid test development and easy maintenance [13].

Keyword-driven testing is a type of functional automation testing framework and its main

advantages are [21]:

Page 36: Information Systems and Computer Engineering

 

26  

- It is best suited for novice or non-technical testers;

- Enables writing tests in a more abstract manner using this approach;

- Keyword driven testing allows automation to be started earlier even before a stable

build is delivered for testing;

- There is a high degree of reusability;

It also has a few downsides:

- Initial investment in developing the keywords and its related functionalities might

take longer.

- It might act as a restriction to the technically abled testers.

In this approach, the keywords are the activities of the BPM diagram which represent the

actions to be done.

The next step is to build the automated test scripts using the identified keywords. This is done

by translating each keyword to a Java method that will be called by the several test scripts, which

are generated automatically by this solution. As stated before, keywords are defined with an action-

descriptive keyword name but since in this dissertation the keywords are Java methods, there is the

restriction as to respect the Java syntax. In other words, although in the BPM diagram point of view

the keywords do have representative names, when they are “converted” to Java methods, the Java

syntax rules must be followed. For that limitation, it is better to use the activities unique id for the

name of the keywords, since it is always a valid name. For the Java methods (keywords)

identification to be easier, Java annotations are used to associate each Java method to the name of

the correspondent activity in the BPM diagram.

This could be seen as a limitation but then again, since this refers to individual BPM diagrams

for each Use Case and not to activities shared by different diagrams (Use Cases) an auxiliary class

(Common Lib) was used, where all the common Java methods (keywords) for the different BPM

diagrams (Use Cases) were implemented. The idea of the Common Lib implementation was, by

some means, to overcome this limitation.

Since each path of the diagram represents a Test Case, it is easy to combine the keywords by the

right order and generating a functional test script.

Each Java method is then implemented manually using automated testing tools, such as

Selenium or SilkTest.

The scripts are then imported to the TestAut framework which will execute the Java methods

using the Robot Framework.

Page 37: Information Systems and Computer Engineering

 

27  

3.4 Automatic Generation of Keywords

Keywords introduced in the previous section are the “heart” of this solution. To automatically

generate them, the BPM diagram needs firstly to be converted in a script language that can be

“parsed”.

BPM modeling tools, like bizagi13 used in this approach, allow building the BPM diagram with

the set of rules and methodology described in section 3.2. Besides that, it is possible to export this

diagram to a XPDL file, which defines a XML schema for specifying the declarative part of a

business process. A Java parser was implemented is this work to make the automatic generation of

the possible keywords from the XPDL file. As explained before, each keyword corresponds to a task

in the BPM diagram. From the XPDL file, each task has a unique identifier. For example: 1eb39e26-

9d54-48b7-a350-5b7eccbaeb89 (figure 13).

Figure 13 ‐ XPDL example (activity unique identifier). 

The implemented Java XPDL Parser (see source code on Annex C) in this solution will generate

automatically the following:

1- Test scripts Java classes (junit files), each corresponding to a Test Case, with methods

(keywords) that map the different activities of the Test Case scenario. For each path in

the BPM diagram it will generate a test script. In this way 100% testing coverage for the

BPM diagram is guaranteed.

2- A Test Library with all the different methods (keywords) used in all test scripts.

The name generated for each method (keyword) is represented by the following rule:

                                                            13 http://www.bizagi.com/ seen on 20/04/2016 

Page 38: Information Systems and Computer Engineering

 

28  

activity_<unique identifier>. In every method there is also a Java annotation with the real name of

the activity on the original BPM diagram (figure 14). Since the name of each method it’s a unique

hexadecimal number, the annotation will facilitate the identification of what the method should

implement. Additionally, in the case of a runtime error, when executing the test scripts, with the

annotation it is possible to know in which keyword (activity from the BPM diagram) the test fails.

This will help to investigate if it is a real bug in the application under testing or if it is a modification

needed to be implemented in the test scripts that came from a change in the requirements (Use Cases

and Business Rules).

To summarize, this Java XPDL Parser, is the main engine and the second important part of this

approach, to generate all the test scripts with all the keywords, in the right order, to cover all the

testing scenarios, from a XPDL file. Reaching this point, the next step is to automate each of the

keywords with the help of a testing Tool Factory. Figure 14 shows an example of a test script (the

“skeleton”).

Figure 14 ‐ Automatic generated test script example. 

 

3.5 Test Library and Factory Pattern  

This is the third and the last important part of this approach: implementing the methods in the

Test Library. As mentioned in section 3.1, the methods called by the test scripts are defined and

implemented in a shared Test Library. This is an important part of the solution since it reduces the

implementation effort. If, for example, 10 test scripts call the same method there is only the need to

implement that method once.

The other imperative part of the solution is the Tool Factory, which gives automation tool

Page 39: Information Systems and Computer Engineering

 

29  

independence through the use of the factory pattern [8, 9]. In this pattern a common Java interface is

defined and implemented by the several supported tools. If the company wants to adopt another

tool, it is only necessary to implement the common interface and all the test scripts done before will

continue to work. As an example of the use of this factory, let’s suppose the following method is

implemented in the Test Library:

@Clicar no botão confirmar public void activity_e5ade915_6533_4fee_b1bf_6702782dac1f() {} 

Instead of calling instructions of the Selenium or the Silktest automation tools, the factory

pattern will be used in the following way:

Define the variables:

private ToolFactory f; 

private Tool t; 

 

Create the factory in the constructor and instantiate the tool interface:

testLibConstructor() { 

f = new TooFactory(); 

 t = f.getTool(); 

}  

Use the interface to call the instructions:

@Clicar no botão confirmar public void activity_e5ade915_6533_4fee_b1bf_6702782dac1f() { 

t.clickById(“confirmar”); 

}  

As a complement to these classes (Test Library and the Tool Factory) it is then possible to add a

project Common Lib as an auxiliary class to contain the objects and methods shared by several BPM

processes.

For instance, the login is a method that all test scripts must do and due to that it makes sense it

is implemented in a common place. So, instead of being implemented in the following way:

@login public void activity_e5ade915_6533_4fee_b1bf_6702782dac1f() { 

    t.writeById(“username”, “20005768354”); t.writeById(“password”, “testes”); t.clickById(“confirmar”); 

}  

 

The project Common Lib can be called with the login implementation: @login public void activity_e5ade915_6533_4fee_b1bf_6702782dac1f() { 

ProjCommonLib.login(t, niss_ee, password); 

}  

 

Page 40: Information Systems and Computer Engineering

 

30  

This is an easy-to-maintain solution and simple to adapt to the evolutions of the application

which will eventually be composed by the following Java classes:

1- The test scripts (generated by the XPDL Parser);

2- The test Tool Factory;

3- The Test Library (where the keywords referenced by the test scripts are

implemented with the help of the test Tool Factory and the project Common Lib);

4- The project Common Lib.

The following diagram, in figure 15, shows how these java classes relate to each other:

 

             

Figure 15 ‐ Relation of the Java classes implemented in the solution. 

An alternative to the project Common Lib would be the sharing of the common keywords

between Use Cases. However, it is not easy to share activities amongst different BPM diagrams. This

would require a manual management of the XPDL file, copying the common activities ids from one

file to another. Besides, the parser would need to support version management, generating new Java

methods only for the activities that have been changed. This could be a future improvement to the

parser.

Page 41: Information Systems and Computer Engineering

 

31  

Proof of Concept Contents

4.1 Proof of Concept Overview ..................................................................................................... 32

4.2 Stage 1 – BPM Modeling ........................................................................................................... 32

4.3 Stage 2 – Generate the XPDL file ........................................................................................ 38

4.4 Stage 3 – Generation of Test Scripts ............................................................................................ 38

4.5 Stage 4 - Implementing the Test Library using the Factory Pattern ............................ 39

4.6 Stage 5 – Running the Test Scripts ................................................................................................ 42

4.7 Evaluating the Results ........................................................................................................................ 44

Page 42: Information Systems and Computer Engineering

 

32  

4.1 Proof of Concept Overview

In this chapter, the new approach presented in this dissertation is tested and evaluated against a

real case. A Portuguese Social Security web application called QLF is used for this proof of concept

and a Use Case and Business Rules were chosen to test the real applicability of this solution.

The Use Case is called UC_001 – Consultar qualificações de trabalhadores de EE. It has a normal

flow with 9 steps and 26 alternate flows (in average each alternate flow has 3 steps). Besides that,

the Use Case references 11 different Business Rules. In total there are 11 full A4 pages describing

this functionality. In figures 5 and 6 (section 2.4) shows sample parts of the Use Case and the

Businesses Rules respectively.

The Test Cases for this Use Case were already designed, months ago, in +Tester tool. It took 2

days for an experience tester to do 57 Test Cases manually and another 2 days to automate them in

Selenium.

To prove this solution, the following stages should be executed and its execution times

measured:

Stage 1 - BPM Modeling: implement a BPM diagram, based on the chosen Use Case and

Business Rules, by applying a set of rules and methodology explained in section 3.2;

Stage 2 – Generate de XPDL file: using the BPM diagram, implemented in previous stage, as

the input to a BPM modeling tool (in this case bizagi), the next step is to export this diagram

to XPDL file format;

Stage 3 – Generation of Tests Scripts: Having the XPDL file from stage 2, using it as the

input for the XPDL Parser, it will automatically generate all the test scripts for this Use Case

and the Test Library;

Stage 4 – Implementing the Test Library using the Factory Pattern: The next step is to

implement in the Test Library the Java methods corresponding to the several activities

(keywords). This should be done using the factory pattern to get tool independence;

Stage 5 – Running the Test Scripts: Reaching this last step, the scripts and the Test Library

need to be uploaded in TestAut (presented in section 2.2) and then, run the test scripts.

4.2 Stage 1 – BPM Modeling

This first stage is a manual process based on the set of rules explained in section 3.2.

As mentioned previously, the BPM diagram should reflect both the business specification (Use

Cases and Business Rules) and the interface specification (Storyboards). Along with the Use Cases

Page 43: Information Systems and Computer Engineering

 

33  

and Business Rules documentation it is also necessary to understand how the application

implements the business. This is specified in Storyboards, which are used in the UP methodology to

model the user interface and the relation between the different screens.

Therefore, to build BPM diagrams, the Business Rules must be mapped to application screens, as

the following image (figure 16) shows. Since each path in the diagram represents a test script, the

activities must be put in the right order to obtain a properly working script.

Figure 16 ‐ Mapping of Use Cases/Business Rules to Screens.

This proof of concept was done for the Use Case introduced in section 2.4 (figure 5) which specifies

the business rules for an operation of the Portal of Portuguese Social Security (PTSS). This operation

allows employers to search information about their worker’s qualifications. To see how the BPM

diagram was built, let’s see how the normal flow of this Use Case was modeled.

The first thing to do is identify the test conditions. For the normal flow the following test conditions

were identified:

- Search by worker data. In this case there are two search criteria:

o By Portuguese Social Security Number

o By Rat id

- Search by workplace and rate. In this search, the options available are:

o Date interval

o Qualification type

o Address of workplace

o Date interval and rate

Having the test conditions identified, the interface specification must be analyzed to see if all these

options for the search are available and how they are mapped to the application screens. The

mapping of the business rules to the application screens for this case has the following result:

Page 44: Information Systems and Computer Engineering

 

34  

1- The first screen is the login page. So, the first thing is to select a user for the login. Due to

performance reasons, the application supports an asynchronous mechanism for users who

have more than 50 employees. This feature changes several things in the application screens.

As a result, the first thing to do in the BPM diagram is to insert 3 activities to support this

behavior:

o Select an employer with more than 50 workers;

o Select an employer with less than 50 workers;

o Select an employer without workers;

2- After the login is done, the user (employer) must select the operation in the menu;

3- Looking at the storyboard screens for that operation, it is easily seen that it has two available

tabs, which supports the two kinds of searches identified in the test conditions above:

a. Tab 1: search by worker data

b. Tab 2: Search by workplace and rate

4- By clicking Tab 1 two searches can be identified in the Use Case:

a. Portuguese Social Security Number

b. Rate id

5- Clicking in Tab 2, the remaining searches can be identified in the Use Case:

a. Date interval

b. Qualification type

c. Address of workplace

d. Date interval and rate

6- For Tab 2 (Search by workplace and rate):

a. If the user has more than 50 workers the interaction with the user is the following:

i. There is a combo box where the user selects the type of the file to be

exported with the worker’s data. The file type can be PDF, XLS or ODS

ii. The request is sent to a queue of asynchronous taks to be processed. When

the file is generated it is sent by email to the user

b. If the employer has less than 50 workers, the user has to do the following:

i. Click the search button

ii. Select the type of file (PDF, XLS or ODS) in a combo box

iii. Save the exported file to the local disk;

iv. In this screen there is also a link to a page where the user can search the

admission details of a specific worker;

7- For Tab 1 (search by worker data), it does not matter if the employer has more or less than 50

users since the search is done for an individual worker. In this case, the screen is equal to Tab

2, with less than 50 users.

8- In the end, the users logout to quit from the application.

Each of the actions identified is then mapped to an activity task in the BPM diagram. The

Page 45: Information Systems and Computer Engineering

 

35  

decisions map to exclusive gateways. In this case we have exclusive gateways to distinguish between

the following conditions:

a) The user selects Tab 1 (search by rorker data) or Tab 2 (search by workplace and rate;

b) The employer has more than 50 workers, less than 50 workers or no workers

c) The employer has workers or has no workers (the user with no workers is the alternative

flow that will be added to the diagram)

As a result, the BPM diagram for the normal flow is presented in figure 17.

It is possible to observe, non-conditional gateways were used to respect the BPMN rules, as

explained in section 3.2.

To finish the diagram, the same approach should be followed for the alternative flows, which

will be connected to the normal flow using link gateways. The complete diagram is shown in figure

18 and it took half-day to implement in bizagi.

Page 46: Information Systems and Computer Engineering

 

36  

Figure 17 ‐ BPM diagram for Use Case (normal flow) – Annex D.

Page 47: Information Systems and Computer Engineering

 

37  

Figure 18 ‐ BPM diagram for complete Use Case ‐ Annex D.

Page 48: Information Systems and Computer Engineering

 

38  

4.3 Stage 2 – Generate the XPDL file

After having modeled the BPM diagram, it is possible to export it to the XPDL format. This file

is generated automatically by the BPM modeling tools and will be the input to the XPDL Parser to

generate all the test scripts. In figure 19 is shown how that can be done in bizagi (the BPM tool used

to model the diagram).

          

Figure 19 ‐ Exporting XPDL file from bizagi. 

 

4.4 Stage 3 – Generation of Test Scripts  

Having the XPDL file, the XPDL Parser can be executed to generate the test scripts and the Test

Library. This parser was implemented from scratch to automatically generate these outputs.

The test script is a junit Java class [11] that calls the activities found in the path. These activities

(keywords) are mapped to Java methods that will be implemented in the Test Library. For the BPM

diagram above (figure 18) the XPDL Parser has generated 72 test scripts and the Test Library

(LibQgenUC001.java) with the java methods corresponding to the activities.

Here is one of the 72 generated test scripts:

package ScriptsQgen; 

 import org.junit.After; import org.junit.Before; import org.junit.Test; import LibQgen.LibQgenUC001; 

 public class Script_1 { 

 private LibQgenUC001 lib; @Before public void setup() { 

lib = new LibQgenUC001(); lib.setup(); 

}        @Test       public void test() { 

@Niss > 50 Trabalhadores lib.activity_6e4754c7_5099_4e20_ac53_d4db95b1286a(); @Login Lib.activity_f1972081_2037_4d32_8379_5e3b632d8cd5(); @Selecionar a operação Menu 

  lib.activity_f6049773_9b48_4964_b453_40891b70afdd(); 

Page 49: Information Systems and Computer Engineering

 

39  

@RN_001: Pesquisa por datas e taxa lib.activity_4c4c2c12_a546_41e1_abe7_18db0079dead(); @Exportar PDF > 50 Trab  libactivity_e0645d43_7003_4455_bd50_5248a079ff18(); @Verificar tabela de dados dos processamentos assincronos lib.activity_7dec8054_7acd_4e46_9a89_0aaeca4d3a1c();  @Logout lib.activity_e5ade915_6533_4fee_b1bf_6702782dac1f(); 

      }       @After       public void tearDown() { 

lib.tearDown();       }          } 

The setup() method creates an instance of the Test Library which is then used in the test()

method to call the activities (keywords) covered by the test script.

4.5 Stage 4 – Implementing the Test Library using the Factory

Pattern The next step is to implement manually, in the Test Library, the Java methods corresponding to

the several activities (keywords). This should be done using the factory pattern to get tool

independence and the project Common Lib. The Tool Factory supports, at the moment, the

Selenium and the SilkTest testing tools, as it can be understood in the following source code:

ToolFactory.java – Java class that allows to choose the tool

package pt.segsocial.internal.aa.weblib; import pt.ii.testaut.lib.Testautlib; 

 public class ToolFactory { 

public Tool getTool() {                 // Opções possíveis para este parâmetro: "Selenium" e "Silktest     String tool = Testautlib.getParam("TOOL","Selenium");  if (tool.equalsIgnoreCase("Silktest")) { 

return new SilktestWeb(); } else { 

return new Selenium(); } 

}    } 

                

This is a very simple class which has only the purpose of choosing the automatization tool. It calls

the TestAaut method getParam to get the value of the parameter TOOL, where the default value is

“selenium”. Based on this value, it instantiates one class or the other. 

The classes SilktestWeb and Selenium, called by the Tool Factory, implement the tool interface, which

has the definition of the methods that should be used by the test scripts. The methods of this interface

were defined by analyzing the instructions sets of the automation tools and the way they work.  

From this analysis two main conclusions were taken: 

1- Both tools, Selenium and SilkTest, identify the objects present in the interface,

essentially by the following elements:

Page 50: Information Systems and Computer Engineering

 

40  

Id;

Name;

Text of the links in a web page;

XPath expressions, which is a query language used in the Web

defined by the World Wide Web Consortium (W3C)

2- The tools have instructions to click, write, clean and check values.

Based on these investigations, the following Java interface has been defined and it contains methods

such as clickById and writeByName, which use these common functionalities. The setup and teardown

methods allow the user to perform actions before the beginning and after the ending of the execution,

such as initializing the tool driver.

Tool.java - interface that hides the details of the tools

package pt.segsocial.internal.aa.weblib; public interface Tool {   public void setup(String url);   public void clickById(String componentId);  public void clickByName(String componentName);   public void clickByXPath(String xPathStr);   public void clickByLinkText(String linkText);   public void writeById(String componentId, String text);  

 public void writeByName(String componentName, String text);   public void writeByXPath(String xpathStr, String text):    

public void clearById(String componentId);  public void clearByName(String componentName);   public void clearByXPath(String xpathStr);  public void StringCheckById(String componentId, String str);   public void StringCheckByName(String componentName, String str);   public void StringCheckByXPath(String xPathStr, String str);   public void StringCheckByLinkText(String linkText, String str);   public void tearDown();    public Object getToolObject(); } 

 

ToolFactory.java – Java class that allows to choose the tool

package pt.segsocial.internal.aa.weblib; import pt.ii.testaut.lib.Testautlib; 

 public class ToolFactory {  

public Tool getTool() {   // Opções possíveis para este parâmetro: "Selenium" e "Silktest  String tool = Testautlib.getParam("TOOL","Silktest"); 

 if (tool.equalsIgnoreCase("Silktest")) { 

return new SilktestWeb(); } else {    return new Selenium(); } 

} } 

Page 51: Information Systems and Computer Engineering

 

41  

The Test Library generated by the XPDL Parser has following structure:

1- The constructor where is created an instance of the Tool Factory;

2- A setup method where all the necessary initializations are done before the start of

the test script execution;

3- A teardown method to do all the cleanup actions at the end of the test script

execution;

4- The Java methods corresponding to the several activities called by the test scripts.

Example of a Test Library:

public class LibQgenUC001 {  

private ToolFactory f; private Tool t; private String niss_ee; private String password; 

 public LibQgenUC001() { 

    f = new ToolFactory();   t = f.getTool(); 

}  

public void setup() {    String baseUrl = Testautlib.getParam("URL","https://quaapp.seg‐social.pt/");   t.setup( baseUrl + "ptss"); 

}  

public void tearDown() {   t.tearDown(); 

}  

@Login public void activity_f1972081_2037_4d32_8379_5e3b632d8cd5() {     PTSSCommons.login(t, niss_ee, password); 

   t.StringCheckById(PTSSCommons.idMsgHomePage, PTSSCommons.textMsgHomePage);  } 

@Selecionar a operação Menu 

       public void activity_f6049773_9b48_4964_b453_40891b70afdd() {      t.clickById("M7612"); 

    @Operação Consultar trabalhadores   t.clickByLinkText("Admissão e cessação de trabalhadores"); 

    t.clickByXPath("//div[@id='navigationArea']/div[2]/a/div/h3");    

}  

@Niss < 50 Trab. public void activity_d830cbf7_1251_49fd_914d_1b6b5556e776() {    

  niss_ee = "25105838736";   password = "testes";     } 

       @Niss > 50 Trab.       public void activity_6e4754c7_5099_4e20_ac53_d4db95b1286a() {     niss_ee = "10031134622";     password = "testes";       }   } 

 

The Test Library generated by the XPDL Parser for figure 18, had 72 test scripts and took 6 hours to

implement.

Page 52: Information Systems and Computer Engineering

 

42  

4.6 Stage 5 – Running the Test Scripts

By succeeding in the previous steps it is then possible to upload both the test scripts and the

Test Library in TestAut (presented in Section 2.2) and proceed to running the test scripts. This is

done in the following order:

1- Upload the test scripts in TestAut

2- Upload the Test Library

3- Associate the Test Library to the test script

4- Add the following parameters to the test script:

TOOL – name of the automation test tool to use (The supported tools at the moment are

Selenium and Silktest)

URL – address of the web application to test

5- Create the Test Cases and associate the corresponding test scripts

6- In the Test Cases enter the values for the parameters TOOL and URL (Selenium or

Silktest)

7- Create a test suite and add the Test Cases

8- Run the suite. This will execute all the Test Cases associated to the suite. This execution

can be done in the following two ways:

a) Launching immediately the execution

b) Scheduling an execution for a given date/time

9- Get the report with the results of the execution, generated by TestAut using the Robot

Framework (Annex B3)

As a result of this approach, the 72 scripts have run with success in both tools supported by the

factory, being very easy to change the automation tool used. It is only necessary to change TOOL

parameter in Testaut to Selenium or SilkTest without the need to compile or do any changes in the

code or in the test scripts.

As previously seen, stage 5 has a manual step and an automatic one. The upload of the test

scripts and Test Library generated by this solution is done in a manual way in TestAut, but the

execution of the test scripts is automatic.

Page 53: Information Systems and Computer Engineering

 

43  

Table 2 shows a summary of which steps are manual and which are automatic in this approach.

Table 2 ‐ Description of the Manual and Automatic steps in this approach 

Manual Automatic  Stage 1: Implementing the BPM diagram from Use Case, Business Rules and Storyboard  

 Stage 2: Exporting the XPDL file from BPM modeling tool 

 Stage 4: Implementing the keywords on the Test Library using the factory pattern  

 Stage 3: Generation of test scripts through the XPLD Parser  

 Stage 5: Upload the test scripts and the Test Library in TestAut  

 Stage 5: Execute the tests scripts in TestAut 

Page 54: Information Systems and Computer Engineering

 

44  

4.7 Evaluating the Results

From the proof of concept, it is possible to compare the current / old approach used in Instituto

de Informática, I.P., with the new approach shown in this dissertation. Table 3 presents the main

conclusions of the comparison:

Table 3 ‐ Comparison between current and new approaches 

Current / old approach New approach Harder and more time consuming:  Manual Test Case took 2 days to design 57 Test Cases and 2 days to automate them in Selenium. 

More simple and less time consuming:  BPM design from Use Case and Business Rules took half‐day to implement in bizagi and the 72 Test Cases (test scripts) were automatically generated. The Test Library took 6 hours to implement. 

Incomplete Test Coverage:  57 Test Cases were produced manually and 15 were missed (human error‐prone). 100% Test coverage hard to achieve. 

Complete Test Coverage:  72 Test Cases (test scripts) were automatically generated with 100% coverage guaranteed 

Automation Testing Tool dependence:  The Test Cases automation process needs to be done with a specific tool: Selenium or SilkTest and the generated scripts are tool dependent. If the tool, for example, gets discontinued and a new tool is adopted, the scripts must be recorded again. 

Automation Testing Tool independence:  The test scripts (Test Cases) generated are tool independent. If the tool changes, it is only necessary to implement the Java interface of the Test factory without the need to change the scripts. 

No reusability and less productivity:  The 57 Test Cases need to be implemented in an automation tool, all of them, from the beginning to the end of each Test Case, without any reusability between test scripts. For instance, the login, that is presented in all Test Cases, needs to be recorded 72 times or copied manually between the scripts 

Good reusability and better productivity:  Using the Test Library, the keywords generated only need to be implemented once. For instance, the login, used in the 72 test scripts (Test Cases), only need to be implemented once and it will be reused the other 71 times 

Harder to maintain:  If the Use Case, Business Rules or the Storyboard changes, the process of updating and maintain the Test Cases and automating the Test Cases that have changed is a hard manual process and the test scripts that need to be changed, also need to be completely automated from the beginning  

Easier to maintain:  If the Use Case, Business Rules or the Storyboard changes, the BPM diagram needs to be updated manually, but it is an easier task to change a graphical diagram than updating text‐only Test Cases and less time consuming. After updating the BPM Diagram, all the test scripts (Test Cases) are automatically generated again and only the keywords that changed need to be implemented again 

Test Cases always need to be designed from Use Cases, Business Rules and Storyboards 

No Test Cases  If the methodology of implementing the BPM diagram from Use Cases, Business Rules and Storyboard is applied in the analysis phase, the tester doesn’t need to do this manual task and the Test Cases are automatically generated from the BPM diagram delivered from the analysis team to the testing team 

Page 55: Information Systems and Computer Engineering

 

45  

Conclusions and Future Work

Contents

5.1 Conclusions ................................................................................................................................. 46

5.2 Future Work ................................................................................................................................................... 46

Page 56: Information Systems and Computer Engineering

 

46  

5.1 Conclusions

In this paper a new approach was presented on how test automation process can be optimized

and be more efficient in the phase of designing and implementing automatic Test Cases. Keyword

driven test approach is not new but this method, as previously shown, demonstrates that with a

new way of designing functional specifications (the input to the Test Cases) it is possible to

automatically generate these keywords, which are “placed” in test scripts with all the possible

combinations and guaranteeing 100% functional specification coverage from the automatic Test

Cases (test scripts) generated through this solution. This method also works for the automatically

generation of manual Test Cases by using the annotations, another benefit from this approach.

Regarding functional specification: Use Cases, Business and Storyboards Rules text documents

are implemented in BPM diagrams with a set of rules described in this dissertation. In the end,

having a functional specification easier to understand, to maintain and with the greater benefit of

generating the test scripts, highlights the additional advantages of this approach.

Finally, this approach demonstrates how automation tool independence can be used for tests

scripts generated with this solution.

5.2 Future Work

The maintenance of Test Cases is a problem when changing of existing Use Cases or Business

Rules occurs. To address this approach, after updating the BPM diagram that maps the Use Cases

Business Rules and Storyboard changes, the set of test scripts can be again automatically generated.

The problem is that all of the keywords are again generated and not only the keywords that are

new or that have changed. Version control on the keywords needs to be implemented in a way that

only the new or changed keyword is generated from the BPM diagram. Related to this, an

alternative to the project Common Lib would be the sharing of the common keywords between Use

Cases (BPM Diagrams).

An additional enhancement would be a methodologic change in Instituto de Informática, I.P.,

regarding the analysis stage where the Use Cases and Business Rules are produced by the system

analysts. It is easy to see all the benefits of diagrams versus text-only documents, and in this case

there is also a greater benefit when using automation testing. The testing team could use directly

the BPM diagram produced from the analysis team, instead of “transforming” the Use Cases,

Business Rules and Storyboard in BPM diagrams. It would be a win-win for both teams.

Direct integration with Instituto de Informática, I.P. testing framework: TestAut is another future

work to develop, as well as implementing more automation tools support besides Selenium and

SilkTest, if needed.

 

Page 57: Information Systems and Computer Engineering

 

47  

Bibliography   

[1] Hetzel, B “The Complete Guide to Software Testing – 2nd Edition”, QED Information Sciences

Inc., 1988

[2] John Watkins, and Simon Mills, “Testing IT”, Cambridge University Press, 2010

[3] Mark Fewster, Dorothy Graham, “Software Test Automation – Effective use of test execution

tools”, ADDISON-WESLEY, 1999

[4] Narayanan Palani, “Software Automation Testing Secrets Revealed”,

BecomeShakespeare.com, 2016

[5] Lisa Crispin, Janet Gregory, “Agile Testing – A Pratical Guide for Testers and Agile Teams”,

Addison-Wesley, 2009

[6] Dorothy Graham, Mark Fewster, “Experiences of Tests Automation”, Addison-Wesley, 2012

[7] Thomas Allweyer, “BPMN 2.0 – Introducing to the Standard for Business Process Modeling”,

BoD, Norderstedt, 2009

[8] Tony Bevis, “Java Design Pattern Essentials – 2nd Edition”, AbilityFIRST, 2012

[9] Alan Richardson, “Java for Testers”, Compedium Developments Ltd, 2015

[10] Alan Richardson, “Selenium Simplified – 2nd Edition”, Compedium Developments Ltd, 2016

[11] Jeff Langr, Andy Hunt, Dave Thomas, “Pragmatic Unit Testing in Java 8 with JUnit – 1st

Edition”, The Pragmatic Programmers, LLC, 2015

[12] SMARTBEAR, “Automated Testing Best Practices and Tips” [Online]. Available

https://smartbear.com/learn/automated-testing/best-practices-for-automation/ seen on

05/02/2016

[13] WIKIBOOKS, “Keyword Test Case Design” [Online]. Available

https://en.wikibooks.org/wiki/Keyword_Test_Case_Design seen on 08/02/2016

[14] Guru99, “Automated Testing: Process, Planning, Tool Selection” [Online]. Available

http://www.guru99.com/automation-testing.html seen on 08/02/2016

[15] OMG, “Business Process Model and Notation” [Online]. Available

http://www.bpmn.org/ seen on 15/03/2016

[16] Robot Framework, “Generic test automation framework for acceptance testing and ATDD”

[Online]. Available http://robotframework.org seen on 15/03/2016

[17] SMARTBEAR, “Top 4 Test Automation Challenges” [Online]. Available

Page 58: Information Systems and Computer Engineering

 

48  

http://blog.smartbear.com/automated-testing/top-4-test-automation-challenges/ seen

on 20/04/2016

[18] Camunda, “BMPN Modeling Reference” [Online]. Available

https://camunda.org/bpmn/reference/ seen on 30/03/2016

[19] WikipediA, “XPDL” [Online]. Available https://en.wikipedia.org/wiki/XPDL seen on

30/03/2016

[20] Fernando Chambel, “Mestrado Integrado em Engenharia Informática – Plataforma de

automação de testes a processos de negócio”, Faculdade de Ciências e Tecnologia,

Universidade Nova de Lisboa, 2015

[21] tutorialspoint, “Keyword Driven Testing” [Online]. Available

http://www.tutorialspoint.com/software_testing_dictionary/keyword_driven_testing.ht

m seen on 01/05/2016

 

Page 59: Information Systems and Computer Engineering

 

  A1 

Annex A – +Tester Screens  

 

 

Page 60: Information Systems and Computer Engineering

 

  B1  

Annex B – TestAut Screens

Editing Test Scripts

Page 61: Information Systems and Computer Engineering

 

  B2  

Editing Test Suites

Page 62: Information Systems and Computer Engineering

 

     B3  

                              

Detail and general reports execution examples

Page 63: Information Systems and Computer Engineering

 

  C1  

Annex C – XPDL Parser source code  import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator;  import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.Node;  import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException;  import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory;  public class XPDLParserSeparatedScripts {     public NodeList getNodeListByXPath(String inputXmlFile, String xPathExpr) {   DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();    DocumentBuilder builder = null;      try {       builder = builderFactory.newDocumentBuilder();   } catch (ParserConfigurationException e) {       e.printStackTrace();          }      Document document = null;      try {       document = builder.parse( new FileInputStream(inputXmlFile));   } catch (SAXException e) {       e.printStackTrace();   } catch (IOException e) {       e.printStackTrace();   }         XPath xPath =  XPathFactory.newInstance().newXPath();             String expression = xPathExpr;               try {    return (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);   } catch (XPathExpressionException e) {      e.printStackTrace();   }      return null;  }     private void printLib (ArrayList<ArrayList<String>> methods, String outputFile) {      String packageName = "ptss.qgen.scripts.lib";   String className = "LibQgenUC001";   String urlParameterName = "URL";   String urlParameterValue = "https://quaapp.seg‐social.pt/";   String urlEndParameter = "ptss";      try    PrintWriter writer = new PrintWriter(outputFile);        writer.println("package " + packageName + ";");    writer.println("");    writer.println("import pt.ii.testaut.lib.Testautlib;");    writer.println("import pt.segsocial.internal.aa.weblib.Tool;");    writer.println("import pt.segsocial.internal.aa.weblib.ToolFactory;");    writer.println("");         writer.println(" public class " + className + " {");    writer.println("");        writer.println("  private ToolFactory f;");    writer.println("  private Tool t;");    writer.println("");        writer.println("  public " + className + "() {");    writer.println("   f = new ToolFactory();");    writer.println("   t = f.getTool();");    writer.println("  }");    writer.println("");        writer.println("  public void setup() {");

Page 64: Information Systems and Computer Engineering

 

    C2  

    writer.println("   String baseUrl = Testautlib.getParam(\"" + urlParameterName +"\",\"" + urlParameterValue+"\");");    writer.println("   t.setup( baseUrl + \"" + urlEndParameter + "\");");    writer.println("  }");    writer.println("");     writer.println("  public void tearDown() {");    writer.println("   t.tearDown();");    writer.println("  }");    writer.println("");            for (ArrayList<String> method: methods) {     for (String line: method) {           writer.println("  " + line);          }         writer.println("");    }        writer.print(" }");          writer.close();                } catch (FileNotFoundException e) {    // TODO Auto‐generated catch block    e.printStackTrace();   }     }    public void generateLib(NodeList activities, String outputFile, ArrayList<String> startGateway, ArrayList<String> endgateways, HashMap<String, String> linkGateways) {      if (startGateway.size() == 0 || endgateways.size() == 0)    return;               ArrayList<ArrayList<String>> methods = new ArrayList<ArrayList<String>>();               for (int i = 0; i < activities.getLength(); i++) {                       org.w3c.dom.Node node = activities.item(i);                                      String id = node.getAttributes().getNamedItem("Id").getNodeValue();             String name = node.getAttributes().getNamedItem("Name").getNodeValue();                           if ((startGateway.contains(id) == false) &&                (endgateways.contains(id) == false) &&                (linkGateways.containsKey(id) == false) &&               (linkGateways.containsValue(id) == false) &&               (name.isEmpty() == false)) {                                                                 id = id.replaceAll("‐", "_");              id = "activity_" + id;                                 ArrayList<String> method = new ArrayList<String>();   

method.add(" @" + name);              method.add("public void " + id + "() {"); 

                                  method.add("}");                            methods.add(method);             }                      }                    printLib(methods, outputFile);  }      private org.w3c.dom.Node getNodeElement(org.w3c.dom.Node node, String elementName) {      NodeList nodeList = node.getChildNodes();     for (int i = 0;i < nodeList.getLength(); i++) {    if(nodeList.item(i).getNodeType() == Node.ELEMENT_NODE)     if (nodeList.item(i).getNodeName().equals(elementName))      return nodeList.item(i);   }       return null;  }    public ArrayList<String> getGateways(String eventName, NodeList activities){          ArrayList<String> gateways = new ArrayList<String>();      for( int i = 0; i < activities.getLength(); i++) {        org.w3c.dom.Node node = getNodeElement(activities.item(i), "Event");        if (node != null) {          for(int j=0; j <node.getChildNodes().getLength();j++ ) {                   if (node.getChildNodes().item(j).getNodeName() == eventName) {             gateways.add(activities.item(i).getAttributes().getNamedItem("Id").getNodeValue());             break;            }     }    }              }      return gateways;

Page 65: Information Systems and Computer Engineering

 

    C3  

  }    public HashMap<String, String> getlinkGateways(NodeList activities) {     HashMap<String, String> throwLinkGateways = new HashMap<String, String>();   HashMap<String, String> catchLinkGateways = new HashMap<String, String>();      for( int i = 0; i < activities.getLength(); i++) {         org.w3c.dom.Node eventNode = getNodeElement(activities.item(i), "Event");        if (eventNode != null) {     org.w3c.dom.Node intermediateEventNode = getNodeElement(eventNode, "IntermediateEvent");         if (intermediateEventNode != null) {      org.w3c.dom.Node triggerResultLinkNode = getNodeElement(intermediateEventNode, "TriggerResultLink");            if (triggerResultLinkNode.getAttributes().getLength() > 0) {       if (triggerResultLinkNode.getAttributes().getNamedItem("CatchThrow").getNodeValue().equals("THROW"))        throwLinkGateways.put(activities.item(i).getAttributes().getNamedItem("Id").getNodeValue(),             activities.item(i).getAttributes().getNamedItem("Name").getNodeValue().toLowerCase().trim());      } else {       catchLinkGateways.put(activities.item(i).getAttributes().getNamedItem("Name").getNodeValue().toLowerCase().trim(),         activities.item(i).getAttributes().getNamedItem("Id").getNodeValue());      }     }            }            }            HashMap<String, String> linkGateways = new HashMap<String, String>();      Iterator<String> iterator = throwLinkGateways.keySet().iterator();        while(iterator.hasNext() ){         String id = iterator.next(); // key     String name =  throwLinkGateways.get(id); // value      if (catchLinkGateways.get(name) != null)      linkGateways.put(id, catchLinkGateways.get(name));     else      System.out.println("Unable to find The catch gateway for the throw gateway " + id );        }      if (linkGateways.size() < throwLinkGateways.size())    return null;       return linkGateways;      }     private void printScripts (ArrayList<ArrayList<String>> scripts, NodeList activities, HashMap<String, String> linkGateways) {      int scriptNumber = 0;   String packageName = "ptss.qgen.scripts";      for (ArrayList<String> script: scripts) {    scriptNumber = scriptNumber + 1;    try {     PrintWriter writer = new PrintWriter("c:\\scripts\\Script_" + scriptNumber + ".java");          writer.println("package " + packageName + ";");     writer.println("");          writer.println("import org.junit.After;");     writer.println("import org.junit.Before;");     writer.println("import org.junit.Test;");     writer.println("");          writer.println("import ptss.qgen.scripts.lib.LibQgenUC001;");     writer.println("");          writer.println("public class Script_" + scriptNumber + " {");     writer.println("");          writer.println(" private LibQgenUC001 lib;");     writer.println("");          writer.println(" @Before");     writer.println(" public void setup() {");     writer.println("");          writer.println("  lib = new LibQgenUC001();");     writer.println("  lib.setup();");      writer.println(" }");     writer.println("");          writer.println(" @Test");     writer.println(" public void test() {");         for(String javaMethod: script) {      

Page 66: Information Systems and Computer Engineering

 

  C4  

            for (int i = 0; i < activities.getLength(); ++i) {                           org.w3c.dom.Node node = activities.item(i);                                                         if (node.getAttributes().getNamedItem("Id").getNodeValue().equals(javaMethod)) {                 String nodeName = node.getAttributes().getNamedItem("Name").getNodeValue();                                                  if (nodeName.isEmpty() || linkGateways.containsKey(javaMethod) || linkGateways.containsValue(javaMethod))                  break;                                  javaMethod = javaMethod.replaceAll("‐", "_");                 javaMethod = "lib.activity_" + javaMethod;                 writer.println(“  @” + nodeName);                 writer.println("  " + javaMethod + "()");                          break;                }                                                    }                         }      writer.println(" }");     writer.println("");          writer.println(" @After");     writer.println(" public void tearDown() {");       writer.println("  lib.tearDown();");     writer.println(" }");                writer.print("}");           writer.close();           } catch (FileNotFoundException e) {     // TODO Auto‐generated catch block     e.printStackTrace();    }      }     }    private Text getConditionExpression (org.w3c.dom.Node transition) {       org.w3c.dom.Node nodeCondition = getNodeElement(transition, "Condition");      if (nodeCondition != null) {        org.w3c.dom.Node nodeExpression = getNodeElement(nodeCondition, "Expression");        if (nodeExpression != null) {     Text textNode = (Text) nodeExpression.getFirstChild();                              return textNode;    }   }     return null;  }     private boolean searchForInvalidConditions(NodeList transitions, NodeList activities) {   // Check for each condition if exists an activity with the same name    HashMap<String, ArrayList<String>> invalidConditions = new HashMap<String, ArrayList<String>> ();              for (int i = 0; i < transitions.getLength(); i++) {              Text condition = getConditionExpression(transitions.item(i));        if (condition != null) {               String[] expressions = condition.getData().split(" or | OR | and | AND ");          if (expressions[0].toLowerCase().trim().startsWith("not"))      expressions[0] = expressions[0].substring(3);          ArrayList<String> invalidExpressions = new ArrayList<String>();          for (String a: expressions) {            invalidExpressions.add(a);                           for (int j = 0; j < activities.getLength(); j++) {              String activityName = activities.item(j).getAttributes().getNamedItem("Name").getNodeValue();              if (activityName.toLowerCase().trim().equals(a.toLowerCase().trim())) {        invalidExpressions.remove(a); // The expression is valid        break;  // Go to the next expression       }      }             }          if (invalidExpressions.size() > 0) {      invalidConditions.put(transitions.item(i).getAttributes().getNamedItem("Id").getNodeValue(), invalidExpressions);     }

Page 67: Information Systems and Computer Engineering

 

  C5  

    }         }        if (invalidConditions.size() == 0)    return false;      Iterator<String> iterator = invalidConditions.keySet().iterator();      while(iterator.hasNext() ) {        String transitionId = iterator.next(); // key    ArrayList<String> invalidExpr =  invalidConditions.get(transitionId); // value         System.out.println("Transition " + transitionId + " with condition expression invalid: ");         for (String e: invalidExpr)      System.out.println("does not exist an activity with the name: " + e);   }            return true;  }    private boolean checkConditionToProceed (ArrayList<String> path, org.w3c.dom.Node transition, NodeList activities) {      Text condition = getConditionExpression(transition);       if (condition == null)    return true;      if (condition.getData().toLowerCase().trim().startsWith("not") ) {    String activity = condition.getData().substring(3);        for (int i = 0; i < activities.getLength(); i++) {          String activityName = activities.item(i).getAttributes().getNamedItem("Name").getNodeValue();          if (activityName.toLowerCase().trim().equals(activity.toLowerCase().trim()))       if (path.contains(activities.item(i).getAttributes().getNamedItem("Id").getNodeValue()) == false)        return true;    }     return false;   }      String[] orExpressions = condition.getData().split(" or | OR ");      // if it was found the or operator, at least one of the expressions found above must be true.   // Otherwise, the expression found must necessarily be true.   // The and operator have precedence over the or operator   for (String expression: orExpressions) {    if (checkExpression(expression, path, activities) == true)     return true;   }    return false;  }    private boolean checkExpression(String expression, ArrayList<String> path, NodeList activities) {      String[] andExpressions = expression.split(" and | AND ");        for (String expr: andExpressions) {    // Get the activity Id and check if the path contains the activity    for (int i = 0; i < activities.getLength(); i++) {          String activityName = activities.item(i).getAttributes().getNamedItem("Name").getNodeValue();           if (activityName.toLowerCase().trim().equals(expr.toLowerCase().trim())) {      if( path.contains(activities.item(i).getAttributes().getNamedItem("Id").getNodeValue()) == true)       break; // Go to the next expression       return false;     }    }   }      return true;  }        public void generateScripts(NodeList activities, NodeList transitions, ArrayList<String> startGateway, ArrayList<String> endGateways, HashMap<String, String> linkGateways) {      ArrayList<ArrayList<String>> scripts = new ArrayList<ArrayList<String>>();   ArrayList<String> activitiesConnectedToStart = new ArrayList<String>();          if (startGateway.size() == 0) {    System.out.println("Start gateway not found");    return;   }      if (endGateways.size() == 0) {    System.out.println("End gateway not found");    return;   }        if (linkGateways == null || searchForInvalidConditions(transitions, activities) == true)    return;

Page 68: Information Systems and Computer Engineering

 

  C6  

         // Get initial activities   for (int i = 0; i < transitions.getLength(); ++i) {    org.w3c.dom.Node node = transitions.item(i);                       if (node.getAttributes().getNamedItem("From").getNodeValue().equals(startGateway.get(0))) {               activitiesConnectedToStart.add(node.getAttributes().getNamedItem("To").getNodeValue());          }   }      // Build path's starting at each one of these initial activities   for (String activity : activitiesConnectedToStart) {    ArrayList<String> path = new ArrayList<String>();    path.add(activity);    scripts.add(path);    dfsSearch(activities, transitions, path, endGateways, scripts, linkGateways);   }       printScripts(scripts, activities, linkGateways);  }        private void dfsSearch(NodeList activities, NodeList transitions, ArrayList<String> path, ArrayList<String> endGateways, ArrayList<ArrayList<String>> scripts, HashMap<String, String> linkGateways) {            ArrayList<String> pathLocalCopy = new ArrayList<String>(path);        // get the activity at the end of the path   String activity = pathLocalCopy.get(path.size() ‐ 1);      // get adjacent activities ‐ activities connected to the activity   ArrayList<String> adjacentActivities = new ArrayList<String>();       for (int i = 0; i < transitions.getLength(); ++i) {    org.w3c.dom.Node transition = transitions.item(i);             if (transition.getAttributes().getNamedItem("From").getNodeValue().equals(activity)) {                            // if we have not reached and end gateway, insert the adjacent activity in the adjacentActivities ArrayList              if (endGateways.contains(transition.getAttributes().getNamedItem("To").getNodeValue()) == false) {                              if ( checkConditionToProceed(pathLocalCopy, transition, activities) == true)                adjacentActivities.add(transition.getAttributes().getNamedItem("To").getNodeValue());               else                scripts.remove(path);              }                          }   }        for (String a : adjacentActivities) {    // search in the scripts ArrayList for a path with the selected activity as the last element.    // If a path is found, the adjacent activity is added.    // If not, a new path is created and the adjacent activity inserted at the end.       // If the activity is a throw link gateway, replace for the corresponding catch gateway     if (linkGateways.containsKey(a))     a = linkGateways.get(a);        ArrayList<String> auxPath = null;    for (int i = 0; i < scripts.size(); i++) {     auxPath = scripts.get(i);     if (scripts.get(i).get(scripts.get(i).size() ‐ 1).equals(activity))      break;        }           if (auxPath != null && auxPath.get(auxPath.size() ‐ 1).equals(activity)) {     // A path was found     auxPath.add(a);    } else {     // create a new path and insert in the scripts ArrayList     auxPath = new ArrayList<String>(pathLocalCopy);        auxPath.add(a);     scripts.add(auxPath);    }     dfsSearch(activities, transitions, auxPath, endGateways, scripts, linkGateways);   }      }      public static void main(String [] args) {      XPDLParserSeparatedScripts parser = new XPDLParserSeparatedScripts();      NodeList activities = parser.getNodeListByXPath("c:\\Temp\\DiagramCGoTo.xpdl", "//Activities/Activity");   NodeList transitions = parser.getNodeListByXPath("c:\\Temp\\DiagramCGoTo.xpdl", "//Transitions/Transition");   ArrayList<String> startGateway = parser.getGateways("StartEvent", activities);      ArrayList<String> endGateways = parser.getGateways("EndEvent", activities);    HashMap<String, String> linkGateways = parser.getlinkGateways(activities);          parser.generateLib(activities, "c:\\scripts\\lib\\LibQgenUC001_v2.java", startGateway, endGateways, linkGateways);   parser.generateScripts(activities, transitions, startGateway, endGateways, linkGateways);     }   } 

Page 69: Information Systems and Computer Engineering

 

      D1  

Annex D – Use Case & Business Rules real sample  

UC_001 – Consultar qualificações de trabalhadores de EE Este  caso  de  uso  tem  como  objectivo  pesquisar  qualificações  e  comunicações  de  vínculo  da  entidade  empregadora  de  acordo  com os critérios identificados.  

Fluxo Normal de Eventos 1. O utilizador  indica que pretende pesquisar qualificações de  trabalhadores  relativas à  respectiva entidade empregadora, 

sendo  recolhidos  os  critérios  de  pesquisa,  de  acordo  com  a  RN_001  –  Critérios  de  Pesquisa  de  qualificações  de 

trabalhadores de EE. 

2. § O sistema verifica os parâmetros de entrada de acordo com a RN_009 – Verificar parâmetros de pesquisa.  

3. § O sistema verifica que existe pelo menos uma qualificação que satisfaça os critérios de pesquisa recolhidos, de acordo 

com a RN_002 – Consultar qualificações de trabalhadores de EE. 

4. É apresentada a informação das qualificações que verificam os critérios de pesquisa recolhidos, de acordo com a RN_002 – 

Consultar qualificações de trabalhadores de EE. 

5. § O sistema verifica que existe pelo menos uma comunicação de vínculo que satisfaça os critérios de pesquisa recolhidos, 

de acordo com a RN_003 – Consultar comunicações de vínculo de EE. 

6. É apresentada a informação das comunicações de vínculo que verificam os critérios de pesquisa recolhidos, de acordo com 

a RN_003 – Consultar comunicações de vínculo de EE. 

7. O utilizador indica que pretende pesquisar as comunicações de vínculo em erro. 

8. § O sistema verifica que existe pelo menos uma comunicação de vínculo em erro que satisfaça os critérios de pesquisa 

recolhidos, de acordo com a RN_004 – Consultar comunicações de vínculo em erro de EE. 

9. É apresentada a  informação das comunicações de vínculo em erro que verificam os critérios de pesquisa recolhidos, de 

acordo com a RN_004 – Consultar comunicações de vínculo em erro de EE.  

Fluxos Alternativos de Eventos 2.a. § O sistema verifica se o parâmetro data de início preenchido então o parâmetro data de fim tem de ser preenchido. 

1. O sistema devolve mensagem “A data de fim tem de ser preenchida quando a data de início é preenchida” 

2. § O utilizador pretende reformular os critérios de pesquisa. 

1. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

2.a.2. O utilizador não pretende reformular os critérios de pesquisa. 

3. O caso de uso termina.  

2.b. § O sistema verifica se o parâmetro data de fim preenchido então o parâmetro data de início tem de ser preenchido. 

1. O sistema devolve mensagem “A data de início tem de ser preenchida quando a data de fim é preenchida” 

2. § O utilizador pretende reformular os critérios de pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

2.b.2. O utilizador não pretende reformular os critérios de pesquisa. 

1. O caso de uso termina.  2.c. § O sistema verifica quando os parâmetros data de  início e data de  fim se encontram preenchidos,  se a data de  início é 

superior à data de fim. 

1. O sistema devolve mensagem “A data de início tem de ser inferior ou igual à data de fim” 

2. § O utilizador pretende reformular os critérios de pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

2.c.2. O utilizador não pretende reformular os critérios de pesquisa. 

1. O caso de uso termina.  2.d. § O sistema verifica se o valor do parâmetro NISS Trabalhador corresponde a um NISS válido existente na Base de dados e 

se corresponde a uma pessoa singular: 

4. O sistema devolve mensagem “O valor do NISS não é um valor válido ou não corresponde a uma Pessoa Singular”

Page 70: Information Systems and Computer Engineering

 

  D2  

1.

2. § O utilizador pretende reformular os critérios de pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

2.d.2. O utilizador não pretende reformular os critérios de pesquisa. 

1. O caso de uso termina.  

2.e. § O sistema verifica se o valor do parâmetro NISS Trabalhador corresponde a um NISS Ativo. 1. O sistema devolve mensagem “O NISS introduzido foi alterado, pelo que, devem passar a utilizar o novo

NISS {0}.”.

2. Fluxo de execução prossegue no ponto 2 do fluxo normal.  

2.f. § O sistema verifica as condições do parâmetro NIF Trabalhador. 1. O sistema devolve mensagem “O valor do NIF não é um valor válido ou não corresponde a uma Pessoa

Singular”

2. § O utilizador pretende reformular os critérios de pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

2.f.2. O utilizador não pretende reformular os critérios de pesquisa. 

1. O caso de uso termina.  2.g. § O sistema apresenta a lista de Locais de Trabalho (estabelecimentos) vazia. 

1. § O utilizador pretende reformular os critérios de pesquisa. 

2. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

2.g.2. O utilizador não pretende reformular os critérios de pesquisa. 

1. O caso de uso termina.  

2.h. § O sistema verifica as condições do parâmetro Taxa. 1. O sistema devolve mensagem “O valor da taxa deve ser um valor numérico compreendido entre 0 e 100 com 2 casas 

decimais” 

2. § O utilizador pretende reformular os critérios de pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

2.h.2. O utilizador não pretende reformular os critérios de pesquisa. 

1. O caso de uso termina.  2.i.  § O  sistema  verifica,  quando  o  parâmetro  Taxa  preenchido,  se  os  parâmetros  Data  Início  e  Data  Fim não  se  encontram 

preenchidos. 1. O sistema devolve mensagem “As datas têm de ser preenchidas quando a taxa é preenchida.” 

2. § O utilizador pretende reformular os critérios de pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

2.i.2. O utilizador não pretende reformular os critérios de pesquisa. 

1. O caso de uso termina.  2.j. § O sistema verifica se o valor do parâmetro NISS EE corresponde a um NISS válido existente na Base de dados. 

1. O sistema devolve mensagem “O valor do NISS não é um valor válido.” 

2. § O utilizador pretende reformular os critérios de pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal. 

 2.j.2. O utilizador não pretende reformular os critérios de pesquisa. 

1. O caso de uso termina.  

2.k. § O sistema verifica se o valor do parâmetro NISS EE corresponde a um NISS Ativo. 

2. § O sistema verifica se o valor do parâmetro NISS EE tem NISS Válido correspondente 

3. O sistema devolve mensagem “O NISS foi alterado, pelo que, devem passar a utilizar o novo NISS {0}.”. 

1. O caso de uso termina.  

2.k.1. O valor do parâmetro NISS EE não tem NISS Válido correspondente 

1. O sistema devolve a mensagem “O NISS foi alterado.” 

2. O caso de uso termina.  3.a. Não existem qualificações que satisfaçam os critérios de pesquisa recolhidos. 

Page 71: Information Systems and Computer Engineering

 

  D3  

 

1. O sistema apresenta a mensagem “Pesquisa sem registos associados”. 

2. § O utilizador pretende efectuar nova pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

3.a.2. O utilizador não pretende efectuar nova pesquisa. 

1. O caso de uso termina.  

5.a. Não existem comunicações de vínculo que satisfaçam os critérios recolhidos. 

1. O sistema apresenta a mensagem “Pesquisa sem registos associados”. 

2. § O utilizador pretende efectuar nova pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

5.a.2. O utilizador não pretende efectuar nova pesquisa. 

1. O caso de uso termina.  

8.a. Não existem comunicações de vínculo em erro que satisfaçam os critérios recolhidos. 

1. O sistema apresenta a mensagem “Pesquisa sem registos associados”. 

2. § O utilizador pretende efectuar nova pesquisa. 

3. Fluxo de execução prossegue no ponto 1 do fluxo normal.  

8.a.2. O utilizador não pretende efectuar nova pesquisa. 

1. O caso de uso termina.  

 

Regras de Negócio 

RN_001 – Critérios de Pesquisa de qualificações de trabalhadores de EE 

1.1.1 Descrição Esta regra de negócio permite definir os critérios de pesquisa de qualificações de trabalhadores por conta de outrem e de membros de órgãos estatutários.  A pesquisa de qualificações será efectuada a partir da selecção do tipo de pesquisa a realizar e do preenchimento dos respectivos critérios identificados: 

1. Trabalhador: 

NISS EE (obrigatório preenchido automaticamente através da autenticação na SSD) 

Data de início da pesquisa (obrigatória quando o parâmetro «Data de fim da pesquisa» seja preenchido) 

Data de fim da pesquisa (obrigatória quando o parâmetro «Data de início da pesquisa» seja preenchido) 

NISS PS 

NIF PS (apenas será preenchido caso o NISS não seja preenchido) 

2. Local de Trabalho e Taxa: 

NISS EE (obrigatório preenchido automaticamente através da autenticação na SSD) 

Data de início da pesquisa (obrigatória quando o parâmetro «Data de fim da pesquisa» seja preenchido e obrigatória 

quando o parâmetro «Taxa» seja preenchido) 

Data de fim da pesquisa (obrigatória quando o parâmetro «Data de início da pesquisa» seja preenchido e obrigatória 

quando o parâmetro «Taxa» seja preenchido) 

Tipo de Qualificação 

Local de Trabalho (Estabelecimento) 

Taxa  

1.2 RN_002 – Consultar qualificações de trabalhadores de EE 

1.2.1 Descrição Esta regra de negócio obtém uma lista de trabalhadores com qualificações efetivas para a entidade empregadora, de acordo com os critérios de pesquisa identificados.  Pesquisar qualificações Obter uma lista de trabalhadores com qualificações, com as características seguintes: 

NISS EE igual ao identificado 

NISS PS igual ao identificado ou NISS PS correspondente ao NIF identificado 

Tipo de Qualificação igual ao identificado 

Local de Trabalho (Estabelecimento) igual ao identificado 

Valor de Taxa Total igual ao identificado

Page 72: Information Systems and Computer Engineering

 

  D4  

 

Data início da qualificação menor ou igual à data de fim da pesquisa 

Data de fim da qualificação nula ou data de fim da qualificação maior ou igual à data de início da pesquisa  Ordenação qualificações Ordenar a lista de resultados por ordem crescente de: 

NISS PS  Resultado de pesquisa qualificações Como resultado de uma pesquisa de qualificações é apresentada, pela ordem indicada, a seguinte informação: 

NISS PS  Nome do trabalhador 

Data de nascimento do trabalhador  

1.3 RN_003 – Consultar comunicações de vínculo de EE 

1.3.1 Descrição Esta regra de negócio obtém a lista de comunicações de vínculo de trabalhadores para a entidade empregadora de acordo com os critérios de pesquisa identificados.  Pesquisar comunicações de vínculo Obter lista de comunicações de vínculo com as seguintes características: 

1. Comunicações de vínculo por processar obtidas através dos pedidos de alteração:  

NISS EE igual ao identificado 

NISS PS igual ao identificado ou NISS PS correspondente ao NIF identificado 

Local de Trabalho (Estabelecimento) igual ao identificado 

Valor de Taxa Total igual ao identificado 

Data da comunicação de vínculo menor ou igual à data de fim da pesquisa 

Data da comunicação de vínculo maior ou igual à data de início da pesquisa 

Operação de criação igual a “EXT‐O001” (Registo Vinculo de Trabalhador pela EE) 

Tipo de Qualificação igual a “TCO” 

2. Comunicações de vínculo em erro obtidas através dos pedidos de alteração em erro: 

NISS EE igual ao identificado 

NISS PS igual ao identificado ou NISS PS correspondente ao NIF identificado 

Local de Trabalho (Estabelecimento) igual ao identificado 

Valor de Taxa Total igual ao identificado 

Data da comunicação de vínculo menor ou igual à data de fim da pesquisa 

Data da comunicação de vínculo maior ou igual à data de início da pesquisa 

Operação de criação pai igual a “EXT‐O001” (Registo Vinculo de Trabalhador pela EE) 

Código de Mensagem de erro: “M2186” (Ocorreu um erro indeterminado.) ou “M3125” (Erro ao Registar 

Notificação.) 

Tipo de Qualificação igual a “TCO” 

Erro Submetido igual a “N”  Ordenação comunicações de vínculo Ordenar a lista de resultados de 1 e 2 por ordem decrescente de: 

Data de comunicação de vínculo  Resultado de pesquisa comunicações de vínculo Como resultado de uma pesquisa de comunicações de vínculo é apresentada, pela ordem indicada, a seguinte informação: 

NISS  Nome do trabalhador 

Data de nascimento do trabalhador 

Data de comunicação de vínculo 

Data de Início de contrato  

1.4 RN_004 – Consultar comunicações de vínculo em erro de EE 

1.4.1 Descrição Esta regra de negócio obtém uma lista de comunicações de vínculo em erro da entidade empregadora de acordo com os critérios de pesquisa identificados.  Pesquisar comunicações de vínculo em erro Obter uma lista de comunicações de vínculo em erro com as seguintes características:

Page 73: Information Systems and Computer Engineering

 

  D5  

 Comunicações de vínculo em erro obtidas através dos pedidos de alteração em erro: 

NISS EE igual ao identificado 

NISS PS igual ao identificado ou NISS PS correspondente ao NIF identificado 

Local de Trabalho (Estabelecimento) igual ao identificado 

Valor de Taxa Total igual ao identificado 

Data da comunicação do vínculo menor ou igual à data de fim da pesquisa 

Data da comunicação do vínculo maior ou igual à data de início da pesquisa 

Operação de criação pai igual a “EXT‐O001” (Registo Vinculo de Trabalhador pela EE) 

Código de Mensagem de erro preenchida e diferente dos valores: “M2186” (Ocorreu um erro indeterminado.) ou 

“M3125” (Erro ao Registar Notificação.) 

Tipo de Qualificação igual a “TCO” 

Erro Submetido igual a “N”  Ordenação comunicações de vínculo em erro Ordenar a lista de resultados por ordem decrescente por: 

Data de comunicação de vínculo  Resultado de pesquisa comunicações de vínculo em erro Como resultado de uma pesquisa de comunicações de vínculo em erro é apresentada, pela ordem indicada, a seguinte informação: 

NISS  Nome do trabalhador 

Data de nascimento do trabalhador 

Data de comunicação do vínculo 

Data de Início de contrato  

1.5 RN_005 – Consultar informação de qualificação  

1.5.1 Descrição Esta regra de negócio obtém a informação de qualificações de acordo com os critérios de pesquisa identificados.  Detalhe de qualificações Obter lista de detalhe de qualificações com as características seguintes: 

NISS EE igual ao identificado 

NISS PS igual ao identificado   Ordenação qualificações Ordenar a lista de resultados de forma decrescente por: 

Data de Qualificação  Resultado de pesquisa de detalhes de qualificações Como resultado de uma pesquisa de detalhe de qualificações é apresentada, pela ordem indicada, a seguinte informação: 

Descrição do Tipo de Qualificação  Data de início do contrato  Data de Fim do contrato 

Valor total da Taxa  

1.6 RN_006 – Consultar informação de local de trabalho (estabelecimento) de qualificação   

1.6.1 Descrição Esta regra de negócio obtém o detalhe de locais de trabalho (estabelecimentos) de acordo com os critérios de pesquisa identificados.  Detalhe de locais de trabalho (estabelecimentos) da qualificação Obter lista de locais de trabalho (estabelecimentos) e períodos de qualificações com as características seguintes: 

NISS EE igual ao identificado 

NISS PS igual ao identificado   Ordenação de locais de trabalho (estabelecimentos) da qualificação Ordenar a lista de resultados de forma decrescente por: 

Data de início  Resultado de pesquisa de locais de trabalho (estabelecimentos) de qualificação Como resultado de uma pesquisa de locais de trabalho (estabelecimentos) de qualificação é apresentada, pela ordem indicada, a seguinte informação: 

Período  De “Data de Início” a “Data de início – 1” do registo anterior ordenado cronologicament

Page 74: Information Systems and Computer Engineering

 

  D6  

 

Local de Trabalho:  o Se morada do local de trabalho (estabelecimento) é portuguesa (país da morada = ‘PT’): 

Código do Estabelecimento||’ – ‘||artéria da morada||’ – ‘||designação do distrito da morada 

o Se morada do local de trabalho (estabelecimento) é estrangeira (país da morada <> ‘PT’): 

Código do Estabelecimento||’ – ‘|| Designação do País  

1.7 RN_007 – Consultar informação de comunicação de vínculo  

1.7.1 Descrição Esta regra de negócio obtém o detalhe de comunicações de vínculo de acordo com os critérios de pesquisa identificados.  Detalhe de comunicação de vínculo Obter lista de detalhe de comunicação de vínculo com as características seguintes: 

Código de Pedido igual ao identificado  Resultado de pesquisa de detalhes de comunicação de vínculo Como resultado de uma pesquisa de detalhe de comunicação de vínculo é apresentada, pela ordem indicada, a seguinte informação: 

Local de Trabalho:  o Se morada do local de trabalho (estabelecimento) é portuguesa (país da morada = ‘PT’): 

Código do Estabelecimento||’ – ‘||artéria da morada||’ – ‘||designação do distrito da morada 

o Se morada do local de trabalho (estabelecimento) é estrangeira (país da morada <> ‘PT’): 

Código do Estabelecimento||’ – ‘|| Designação do País 

Valor total da Taxa 1.7.2 Fundamentação Não aplicável   

1.8 RN_008 – Consultar informação de comunicação de vínculo em erro   

1.8.1 Descrição Esta regra de negócio obtém o detalhe de comunicações de vínculo em erro de acordo com os critérios de pesquisa identificados.  Detalhe de comunicação de vínculo em erro Obter lista de detalhe de comunicação de vínculo em erro com as características seguintes: 

Código de Pedido igual ao identificado  Resultado de pesquisa de detalhes de comunicação de vínculo em erro Como resultado de uma pesquisa de detalhe de comunicação de vínculo em erro é apresentada, pela ordem indicada, a seguinte informação: 

Local de Trabalho:  o Se morada do local de trabalho (estabelecimento) é portuguesa (país da morada = ‘PT’): 

Código do Estabelecimento||’ – ‘||artéria da morada||’ – ‘||designação do distrito da morada 

o Se morada do local de trabalho (estabelecimento) é estrangeira (país da morada <> ‘PT’): 

Código do Estabelecimento||’ – ‘|| Designação do País 

Valor total da Taxa  Descrição da mensagem de erro 

Data de processamento  

1.9 RN_009 – Verificar parâmetros de pesquisa 

1.9.1 Descrição Esta regra permite efectuar a validação dos parâmetros de pesquisa para obtenção de qualificações de trabalhadores de EE.  A informação dos parâmetros de entrada é considerada válida desde que se verifiquem cumulativamente as seguintes condições:

Page 75: Information Systems and Computer Engineering

 

  D7  

  

Parâmetro de entrada  Condição a validar 

Data de Início 

Quando preenchida: 

Data de Fim tem de estar preenchida 

Data de Início inferior ou igual à data de fim. 

Data de Fim 

Quando preenchida: 

Data de Início tem de estar preenchida 

Data de Fim superior ou igual à data de Início. 

NISS Trabalhador  NISS válido existente na base de dados, correspondente a uma Pessoa Singular 

NISS Ativo 

NIF Trabalhador  NIF válido existente na base de dados, correspondente a uma Pessoa Singular 

Tipo de Qualificação 

Lista de valores possíveis: 

Todos 

Trabalhador por Conta de Outrem 

Membro de Órgão Estatutário 

Local de Trabalho (estabelecimento) 

Obter uma lista de locais de trabalho (estabelecimentos) da EE com as características seguintes: 

NISS EE igual ao identificado 

Caso, data de início de pesquisa e data de fim de pesquisa se encontrem preenchidos, 

então, a lista apresentada é restrita aos locais de trabalho (estabelecimentos) que se 

encontrem ativos no respectivo período 

Caso, data de início de pesquisa e data de fim de pesquisa não se encontrem 

preenchidos, então, não é efectuada restrição por datas nem estado do 

estabelecimento. Resultado de Pesquisa de Locais de Trabalho (estabelecimentos) EE: Como resultado da pesquisa de locais de trabalho (estabelecimentos) da EE é apresentada, a seguinte informação ordenada por ordem crescente: 

o  Se morada do local de trabalho (estabelecimento) é portuguesa (país da morada = 

‘PT’): 

Código do Estabelecimento||’ – ‘||artéria da morada||’ – 

‘||designação do distrito da morada 

o  Se morada do local de trabalho (estabelecimento) é estrangeira (país da morada 

<> ‘PT’): 

Código do Estabelecimento||’ – ‘|| Designação do País 

Taxa 

Valor numérico decimal compreendido entre 0 e 100 inclusive com 2 casas decimais. Quando preenchida: 

Data de Início tem de estar preenchida 

Data de Fim tem de estar preenchida 

NISS EE 

NISS válido existente na base de dados, correspondente a uma Pessoa Coletiva ou a uma 

Pessoa Singular 

NISS Ativo 

 

1.10 RN_010 – Consultar informação de suspensões  

1.10.1 Descrição Esta regra de negócio obtém a informação de suspensões associadas à qualificação de acordo com os critérios de pesquisa identificados.  Detalhe de qualificações Obter lista de detalhe de suspensões de qualificações com as características seguintes: 

NISS EE igual ao identificado 

NISS PS igual ao identificado   Ordenação de suspensões Ordenar a lista de resultados de forma decrescente por: 

Data de Início de suspensão  Resultado de pesquisa de suspensões de qualificação Como resultado de uma pesquisa de suspensões de qualificação é apresentada, pela ordem indicada, a seguinte informação: 

Data de início da suspensão  Data de Fim da suspensão 

Designação do motivo de suspensã

Page 76: Information Systems and Computer Engineering

 

  D8  

  

1.11 RN_011 – Verificar se número de trabalhadores da EE superior ou igual a 50 

1.11.1 Descrição Esta regra de negócio verifica se determinada entidade empregadora tem mais de 50 trabalhadores.  Obter número distinto de NISS’s PS de qualificações genéricas com as características seguintes: 

NISS EE igual ao identificado Verifica se o valor retornado: 

Superior ou igual a 50 

Inferior a 50  Nota:  Se o valor retornado inferior a 50 então no ecrã será apresentado o botão de pesquisa. Caso, o valor retornado seja superior ou igual a 50 então no ecrã não será apresentado o botão de pesquisa, sendo apresentado um link para geração da informação para fichei