1. Trang chủ
  2. » Công Nghệ Thông Tin

Java for testers learn java fundamentals fast alan richardson

291 127 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 291
Dung lượng 1,68 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Most Java books start with a ‘main’ class and show how to compile code and write simpleapplications from the command line, then build up into more Java constructs and GUIapplications.. B

Trang 2

e-book ISBN : 978-0-9567332-4-5

© 2013 - 2015 Alan Richardson, Compendium Developments Ltd

Trang 3

As ever This book is dedicated to Billie and Keeran.

Trang 9

Chapter Twenty One - Collections Revisited

Trang 10

This is an introductory text At times it takes a tutorial approach and adopts step by stepinstructions to coding Some people more familiar with programming might find this slow.This book is not aimed at those people

This book is aimed at people who are approaching Java for the first time, specifically with

a view to adding automation to their test approach I do not cover automation tools in thisbook

I do cover the basic Java knowledge needed to write and structure code when automating

I primarily wrote this book for software testers, and the approach to learning is orientedaround writing automation code to support testing, rather than writing applications Assuch it might be useful for anyone learning Java, who wants to learn from a “test first”perspective

Automation to support testing is not limited to testers anymore, so this book is suitable foranyone wanting to improve their use of Java in automation: managers, business analysts,users, and of course, testers

Testers use Java differently

I remember when I started learning Java from traditional books, and I remember that I wasunnecessarily confused by some of the concepts that I rarely had to use e.g creating

manifest files, and compiling from the command line

Testers use Java differently

Most Java books start with a ‘main’ class and show how to compile code and write simpleapplications from the command line, then build up into more Java constructs and GUIapplications When I write Java, I rarely compile it to a standalone application, I spend alot of time in the IDE, writing and running small checks and refactoring to abstractionlayers

By learning the basics of Java presented in this book, you will learn how to read and

understand existing code bases, and write simple checks using JUnit quickly You will notlearn how to build and structure an application That is useful knowledge, but it can belearned after you know how to contribute to the Java code base with JUnit tests

My aim is to help you start writing automation code using Java, and have the basic

knowledge you need to do that This book focuses on core Java functionality rather than alot of additional libraries, since once you have the basics, picking up a library and learninghow to use it becomes a matter of reading the documentation and sample code

Exclusions

Trang 11

Some people may look disparagingly on the text based on the exclusions So consider this

an opinionated introduction to Java because I know that I did not need to use many ofthose exclusions for the first few years of my automation programming

I maintain that there is a core set of Java that you need in order to start writing automationcode and start adding value to automation projects I aim to cover that core in this book.Essentially, I looked at the Java I needed when I started writing automation to support mytesting, and used that as scope for this book While knowledge of Interfaces, Inheritance,and enums, all help make my automation abstractions more readable and maintainable; Idid not use those constructs with my early automation

I also want to keep the book small, and approachable, so that people actually read it andwork through it, rather than buying and leaving on their shelf because they were too

intimidated to pick it up And that means leaving out the parts of Java, which you can pick

up yourself, once you have mastered the concepts in this book

This book does not cover any Java 1.8 functionality The highest version of Java required

to work with this book is Java 1.7 The code in this book will work with Java 1.8, I simplydon’t cover any of the new functionality added in Java 1.8 because I want you to learn thebasics, and start being productive quickly After you complete this book, you should beable to pick up the new features in Java 1.8 when you need them

e.g

The main folder for Chapter 3 is:

src\test\java\com\javafortesters\chap003myfirsttest

it contains an examples folder with all the code used in the main body of the text

it contains an exercises folder with all the code for the answers I created for theexercises in Chapter 3

Trang 12

Alan Richardson has worked as a Software professional since 1995 (although it feelslonger) Primarily working with Software Testing, although he has written commercialsoftware in C++, and a variety of other languages

readability

Special thanks go to the following people who provided early and helpful feedback duringthe writing process: Jay Gehlot, Faezeh Seyedarabi, Szymon Kazmierczak, Srinivas

Kadiyala, Tony Bruce, James ‘Drew’ Cobb, Adrian Rapan

I am also grateful to every Java developer that I have worked with who took the time toexplain their code You helped me observe what a good developer does and how they

Trang 13

All mistakes in this book are my fault If you find any, please let me know via

compendiumDev.co.uk/contact or via any of the sites mentioned above

Trang 14

Then in later pages, I will explain the code constructs in more detail, you will write somecode, and I’ll reinforce the explanations

Trang 15

file system, this allows us to find, and use, the Class in the rest of our code

A class with a method

A class, on its own, doesn’t do anything We have to add methods to the class before we can do anything Methods are the commands we can call, to make something happen.

In the following example I have created a new class called AClassWithAMethod, and thisclass has a method called aMethodOnAClass which, when called, prints out "Hello World"

5 public void aMethodOnAClass (){

6 System out println ( "Hello World" );

7 }

8 }

Method names start with lowercase letters

When we start learning Java we will call the methods of our classes from within JUnit tests.

9 public void canOutputHelloWorldToConsole (){

10 AClassWithAMethod myClass = new AClassWithAMethod ();

When I run this method then I will see the following text printed out to the Java console in

my IDE:

Trang 16

Summary

I have thrown you into the deep end here; presenting you with a page of possiblegobbledygook And I did that to introduce you to a the Java Programming Languagequickly

Trang 17

Chapter Summary

In this chapter you will learn the tools you need to program in Java, and how to install them You will also find links to additional FAQs and Video tutorials, should you get stuck.

I have created a support page for installation, with videos and links to troubleshootingguides

JavaForTesters.com/install

If you experience any problems that are not covered in this chapter, or on the supportpages, then please let me know so I can try to help, or amend this chapter, and possiblyadd new resources to the support page

Do you already have JDK or Maven installed?

Trang 18

Java JDK

Many of you will already have a JRE installed (Java Runtime Environment), but whendeveloping with Java we need to use a JDK

If you type javac -version at your command line and get an error saying that javac can not be found (or something similar) Then you need to install and configure a JDK

If you see something similar to:

javac 1.7.0 _10

Then you have a JDK installed It is worth following the instructions below to check ifyour installed JDK is up to date, but if you have a 1.7.x JDK (or higher) installed then youhave a good enough version to work through this book without amendment If your JDK isversion 1.6 then some of the code examples will not work

Java Has Multiple Versions

The Java language improves over time With each new version adding new features If you are unfortunate enough to not be allowed to install Java 1.7 at work (then I suggest you work through this book at home,

or on a VM), then parts of the source code will not work and the code you download for this book will

throw errors.

Specifically, we cover the following features introduced in Java 1.7:

The Diamond operator <> in the Collections chapters Binary literals e.g 0b1001

Underscores in literals e.g 9_000_000_000L switch statements using String s

The above statements may not make sense yet, but if you are using a version of Java lower than 1.7 then you can expect to see these concepts throw errors with JDK 1.6 or below.

Install Maven

Maven requires a version of Java installed, so if you checked for Java and it wasn’t there,you will need to install Maven

If you type mvn -version at your command line, and receive an error that mvn can not

be found (or something similar) Then you need to install and configure Maven beforeyou follow the text in this book

If you see something similar to:

Apache Maven 3.0.4 (r1232337; 2012-01-17 08:44:56+0000 )

Maven home : C \ mvn \ apache - maven -3.0.4

Java version : 1.7.0 _10, vendor : Oracle Corporation

Java home : C \ Program Files \ Java \ jdk1 7.0 _10 \ jre

Default locale : en_GB, platform encoding : Cp1252

OS name : "windows 8", version : "6.2", arch : "amd64", family : "windows"

Trang 19

Install The Java JDK

The Java JDK can be downloaded from oracle.com If you mistakenly download from

java.com then you will be downloading the JRE, and for development work we need theJDK

oracle.com/technetwork/java/javase/downloads

From the above site you should follow the installation instructions for your specific

platform

You can check the JDK is installed by opening a new command line and running thecommand:

Create an M2_HOME user/environment variable that points to the above directory

Create an M2 user/environment variable that points to M2_HOME\bin

Trang 20

You can check it is installed by opening up a new command line and running the

command:

mvn -version

This should show you the version number that you just installed and the path for yourJDK

I recommend you take the time to read the “Maven in 5 Minutes” guide on the officialMaven web site:

maven.apache.org/guides/getting-started/maven-in-five-minutes.html

Install The IDE

While the code in this book will work with any IDE, I recommend you install IntelliJ Ifind that IntelliJ works well for beginners since it tends to pick up paths and defaultlocations better than Eclipse

For this book, I will use IntelliJ and any supporting videos I create for this book, or anyshort cut keys I mention relating to the IDE will assume you are using IntelliJ

The official IntelliJ web site is jetbrains.com/idea

IntelliJ comes in two versions a ‘Community’ edition which is free, and an ‘Ultimate’edition which you have to pay for

I suggest you stick with IntelliJ until you are more familiar with Java because then youminimize the risk of issues with the IDE confusing you into believing that you have aproblem with your Java

Trang 21

the .iml file has other IntelliJ configuration details,

the pom.xml file is your Maven project configuration file

If the wizard created any .java files in any of the directories then you can delete them asthey are not important You will be starting this project from scratch

The above directory structure is a standard Maven structure Maven expects certain files to

be in certain directories to use the default Maven configuration Since you are just startingyou can leave the directory structure as it is

Certain conventions that you will follow to make your life as a beginning developer

easier:

Add your JUnit Test Classes into the src\test\java folder hierarchy

When you create a JUnit Test Class, make sure you append Test to the Class name

The src\main\java folder hierarchy is for Java code that is not used for asserting

behaviour Typically this is application code We will use this for our abstraction layercode We could add all the code we create in this book in the src\test\java hierarchy butwhere possible I split the abstraction code into a separate folder

The above convention description may not make sense at the moment, but hopefully it willbecome clear as you work through the book Don’t worry about it now

The pom.xml file will probably look like the following:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns= "http://maven.apache.org/POM/4.0.0"

Trang 22

xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0

http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>javaForTesters</groupId>

<artifactId>javaForTesters</artifactId>

<version>1.0-SNAPSHOT</version>

We basically edit the pom.xml file to include a dependency on JUnit We do this by

creating a dependencies XML element and a dependency XML element which defines theversion of JUnit we want to use At the time of writing it is version 4.11

The pom.xml file that we will use for this book, only requires a dependency on JUnit, so itlooks like this:

<groupId>javaForTesters</groupId>

<artifactId>javaForTesters</artifactId>

<version>1.0-SNAPSHOT</version>

<packaging>jar</packaging>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

Trang 23

<artifactId>maven-compiler-plugin</artifactId>

Amend your pom.xml file to contain the dependencies and build elements above IntelliJ

Trang 24

If you do get stuck then try and use your favourite search engine and copy and paste theexact error message you receive into the search engine and you’ll probably find someoneelse has already managed to resolve your exact issue

Trang 26

It has the word Test at the end We can take advantage of the ‘out of the box’ Maven

functionality to run our JUnit tests from the command line, instead of the IDE, by typing

mvn test This might not seem important now, but at some point we are going to want torun our code automatically as part of a build process And we can make that easier if weadd Test in the Class name, either as the start of the class name, or at the end By naming

believe it is running.

This leaves us thinking we have more coverage than we actually do.

It uses camel case where each ‘word’ in a string of concatenated words starts with an

uppercase letter This again is a Java convention, it is not enforced by the compiler Butpeople reading your code will expect to see it written like this

Trang 27

As you code, if you see a little pop up in IntelliJ which says “Maven Projects need to be imported” Click the “Enable Auto-Import” This will make your life easier as it will automatically add import statements in your code and update when you change your pom.xml file.

I right click on the java folder under test and select the New \ Java Class menu item

Or, I could click on the java folder under test and use the keyboard shortcut alt + insert, and select Java Class (on a Mac use ctrl + n)

Type in the name of the Java class that you want to create i.e MyFirstTest and select

[OK]

Don’t worry about the package structure for now We can easily manually move our codearound later Or have IntelliJ move it around for us using refactoring

Trang 28

chap003 prefix, but it might help you trace your code back to the chapter in the book I usethis convention to help you find the example and exercise source code in the source

Trang 29

package com javafortesters chap003myfirsttest examples ;

The semi-colon at the end of the line is important because Java statements end with asemi-colon

IntelliJ will highlight this line with a red underscore because our class is not in a folderstructure that represents that package

IntelliJ can do more than just tell us what our problems are, it can also fix this problem for

us if we click the mouse in the underscored text, and then press the keys alt + return.IntelliJ will show a pop up menu which will offer us the option to:

The Empty Class Explained

package com javafortesters chap003myfirsttest examples ;

public class MyFirstTest {

}

If you’ve followed along then you will have an empty class, in the correct package and theProject window will show a directory structure that matches the package hierarchy youhave created

Package Statement

The package statement is a line of code which defines the package that this class belongsin

package com javafortesters chap003myfirsttest examples ;

When we want to use this class in our later code then we would import the class from thispackage

The package maps on to the physical folder structure beneath your src\test folder So ifyou look in explorer under your project folder you will see that the package is actually anested set of folders

Trang 30

+ chap003myfirsttest

+ examples

Java classes only have to be uniquely named within a package So I could create anotherclass called MyFirstTest and place it into a different package in my source tree and Javawould not complain I would simply have to import the correct package structure to getthe correct version of the class

Here the class has public scope This means that any class, in any package, can use thisclass if they import it

In this case the class body is empty, because we haven’t written any code yet, but we stillneed to have the block markers, otherwise it will be invalid Java syntax and your IDE willflag the code as being in error

public class MyFirstTest {

public void canAddTwoPlusTwo (){

}

Trang 31

{}

In order to write code in a method we add it in the code block of the method body i.e.inside the opening and closing braces

JUnit implements a few annotations that we will learn The first, and most fundamental, isthe @Test annotation JUnit only runs the methods which are annotated with @Test as

JUnit tests We can have additional methods in our classes without the annotation, and

JUnit will not try and run those

Trang 32

When you type @Test on the line before the method declaration The IDE will highlight it

If you select the wrong import

If you accidentally select the wrong import then simply delete the existing import statement from the code, and then use IntelliJ to alt + return and import the correct class and package.

An int has limits

An int can store values from -2,147,483,648 to 2,147,483,647 e.g.

int minimumInt = -2147483648;

int maximumInt = 2147483647;

When I create the variable I will set it to 2+2

Trang 33

haven’t imported the assertEquals method or Assert class from JUnit

To fix the error I will alt + return on the assertEquals statement and choose to:

static import method…

from

Assert.assertEquals in the org.junit package

IntelliJ will then add the correct import statement into my code

import static org junit Assert assertEquals ;

The assertEquals method is polymorphic Which simply means that it can be used with

Trang 34

4 is an int literal that represents the expected value, i.e I expect 2+2 to equal 4

answer is the int variable which has the actual value I want to check against theexpected value

I could have written the assert as:

assertEquals (4, answer );

In this form, I have not added a message, so if the assert fails there are fewer clues telling

me what should happen, and in some cases I might even have to add a comment in thecode to explain what the assert does

I try to remember to add a message when I use the JUnit assert methods because it makesthe code easier to read and helps me when asserts do fail

Note that in both forms, the expected result is the parameter, before the actual result.

If you get these the wrong way round then JUnit won’t throw an error, since it doesn’tknow what you intended, but the output from a failed assert would mislead you e.g if Iaccidentally wrote 2+3 when initializing the int answer, and I put the expected and actual result the wrong way round, then the output would say something like:

Trang 35

ctrl + shift + F10

Since we only have one @Test annotated method at the moment they will both achieve thesame result, but when you have more than one @Test annotated method in the class thenthe ability to run individual methods, rather than all the methods in the class can come invery handy

Run all the @Test annotated methods from the command line

If you know how to use the command line on your computer, and change directory thenyou can also run the @Test annotated methods from the command line using the

This book differs from normal presentations of Java, because they would start with

creating simple applications which you run from the command line

When we write automation code, we spend a lot of time working in the IDE and runningthe @Test annotated methods from the IDE, so we code and run Java slightly differentlythan if you were writing an application

This also means that you will learn Java concepts in a slightly different order than otherbooks, but everything you learn will be instantly usable, rather than learning things in

Trang 36

Although there is not a lot of code, we have covered the basics of a lot of important Javaconcepts

Run JUnit Test ctrl + shift + F10 ctrl + shift + F10

Trang 37

without Test e.g NameClass runs in the IDE but not from mvn test

Trang 38

How to access static fields and constants on a class

The difference between Integer value and instantiation

In this chapter you are going to learn how to use other classes in your @Test method code.Eventually these will be classes that you write, but for the moment we will use other

classes that are built in to Java

You have already done this in the previous chapter Because you used the JUnit Assertclass to check conditions, but we imported it statically, so you might not have noticed (I’llexplain what static import means in the next chapter)

But first, some guidance on how to learn Java

Use @Test methods to understand Java

When I work with people learning Java, I encourage them to write methods and assertionswhich help them understand the Java libraries they are using

For example, you have already seen a primitive type called an int

intValue - return an int primitive

longValue - return a long primitive

shortValue - return a short primitive

Explore the Integer class with @Test methods

In fact you can see for yourself the methods available to an integer

Create a new package:

com.javafortesters.chap004testswithotherclasses.examples

Trang 39

Integer four = new Integer (4);

Because Integer is a class, this is called instantiating a class and the variable is an object variable.

int was a primitive type.

Integer is a class

To use a class we instantiate it with the new keyword

The new keyword creates a new instance of a class

The new instance is referred to as an object or an instance of a class

You can also see that I passed in the literal 4 as a parameter I did this because the Integer

class has a constructor method which takes an int as a parameter so the object has a value

The Integer class actually has more than one constructor You can see this for yourself

Type in the statement to instantiate a new Integer object with the value 4

Click inside the parentheses where the 4 is, as if you were about to type a new

parameter,

press the keys ctrl + p (cmd + p on a Mac)

Trang 40

an Integer it can accept an int or a String

Check that intValue returns the correct int

We know that the Integer class has a method intValue which returns an int, so we cancreate an assertion to check the returned value

Assert that intValue returns the Integer 5

Integer five = new Integer ( "5" );

assertEquals ( "intValue returns int 5" ,

5, five intValue ());

Quick Summary

It might not seem like it but we just covered some important things there

Did you notice that you didn’t have to import the Integer class?

Because the Integer class is built in to the language, we can just use it Thereare a few classes like that, String is another one The classes do exist in a

package structure, they are in java.lang, but you don’t have to import them touse them

We just learned that to use an object of a class, that someone else has provided, orthat we write, we have to instantiate the object variables using the new keyword.Use ctrl + p to have the IDE show you what parameters a method can take (cmd +

associated class automatically

Ngày đăng: 20/03/2018, 09:13