Java For Testers Learn Java Fundamentals Fast - Alan Richardson.pdf

  • Stark State College
  • BIO 101
  • Lab Report
  • CrazyRussianHacker293
  • 291
  • 67% (3) 2 out of 3 people found this document helpful

This preview shows page 1 out of 291 pages.

Unformatted text preview: Java For Testers Learn Java fundamentals fast This version was published on 2015-02-27 The right of Alan Richardson to be identified as the author of this work has been asserted by him in accordance with the Copyright, Design and Patents Act 1988. The views expressed in this book are those of the author. First published in Great Britain in 2015 by: Compendium Developments contact details: [email protected] Related WebSites: Java For Testers: javaForTesters.com Author’s Software Testing Blog: eviltester.com Compendium Developments: compendiumdev.co.uk Author’s Selenium Blog: seleniumSimplified.com Every effort has been made to ensure that the information contained in this book is accurate at the time of going to press, and the publishers and author cannot accept any responsibility for any errors or omissions, however caused. No responsibility for loss or damage occasioned by any person acting, or refraining from action, as a result of the material in this publication can be accepted by the editor, the publisher or the author. Apart from any fair dealing for the purposes of research or private study, or criticism or review, as permitted under the Copyright, Design and Patents Act 1988; this publication may only be reproduced, stored or transmitted, in any form or by any means, with the prior permission of the publishers, or in the case of reprographic reproduction in accordance with the terms and licenses issued by the Copyright Licensing Agency, 90 Tottenham Court Road, London, W1T 4LP. Enquiries concerning reproduction outside these terms should be sent to the publishers. e-book ISBN : 978-0-9567332-4-5 © 2013 - 2015 Alan Richardson, Compendium Developments Ltd As ever. This book is dedicated to Billie and Keeran. Table of Contents Introduction Testers use Java differently Exclusions Supporting Source Code About the Author Acknowledgments Chapter One - Basics of Java Revealed Java Example Code Chapter Two - Install the Necessary Software Introduction Do you already have JDK or Maven installed? Install The Java JDK Install Maven Install The IDE Create a Project using the IDE About your new project Add JUnit to the pom.xml file Summary Chapter Three - Writing Your First Java Code My First JUnit Test Prerequisites Create A JUnit Test Class Create a Method Make the method a JUnit test Calculate the sum Assert the value Run the @Test method Summary References and Recommended Reading Chapter Four - Work with Other Classes Use @Test methods to understand Java Warnings about Integer Summary References and Recommended Reading Chapter Five - Working with Our Own Classes Context First create an @Test method Write code that doesn’t exist New Requirements Now Refactor Summary Chapter Six - Java Classes Revisited: Constructors, Fields, Getter & Setter Methods Context Constructor Getters and Setters Summary References and Recommended Reading Chapter Seven - Basics of Java Revisited Comments Statement Packages Java Classes Importing Classes Static Imports Data Types Operators Strings Summary References and Recommended Reading Chapter Eight - Selections and Decisions Ternary Operators if statement else statement Nested if else switch statement Summary References and Recommended Reading Chapter Nine - Arrays and For Loop Iteration Arrays Exercises Summary References and Recommended Reading Chapter Ten - Introducing Collections A Simple Introduction Iterating with while and do…while Interfaces Summary References and Recommended Reading Chapter Eleven - Introducing Exceptions What is an exception? Catching Exceptions An Exception is an object Catch more than one exception JUnit and Exceptions Throwing an Exception finally Summary References and Recommended Reading Chapter Twelve - Introducing Inheritance Inheritance Inherit from Interfaces and Abstract Classes Summary References and Recommended Reading Chapter Thirteen - More About Exceptions Unchecked and Checked Exceptions Difference between Exception, Error and Throwable Create your own Exception class Summary References and Recommended Reading Chapter Fourteen - JUnit Explored @Test Before & After @Ignore JUnit Assertions Asserting with Hamcrest Matchers and assertThat fail static importing Summary References and Recommended Reading Chapter Fifteen - Strings Revisited String Summary System.out.println Special character encoding String Concatenation Converting to/from a String Constructors Comparing Strings Manipulating Strings Basic String parsing with split Manipulating strings With StringBuilder Concatenation, .format, or StringBuilder Summary References and Recommended Reading Chapter Sixteen - Random Data Math.random java.util.random Seeding random numbers Using Random Numbers to generate Random Strings Discussion random data in automation Summary References and Recommended Reading Chapter Seventeen - Dates and Times currentTimeMillis and nanoTime Date SimpleDateFormat Calendar Summary References and Recommended Reading Chapter Eighteen - Properties and Property Files Properties Basics Java’s System Properties Working with Property files Summary References and Recommended Reading Chapter Nineteen - Files Example of reading and writing a file File Writing And Reading Files Additional File Methods Files Summary References and Recommended Reading Chapter Twenty - Math and BigDecimal BigDecimal Math Summary References and Recommended Reading Chapter Twenty One - Collections Revisited Set Map Implementations Summary References and Recommended Reading Chapter Twenty Two - Advancing Concepts Interfaces Abstract Classes Generics Logging Enum Regular Expressions Reflection Annotations Design Patterns Concurrency Additional File considerations Summary Chapter Twenty Three - Next Steps Recommended Reading Recommended Videos Recommended Web Sites Next Steps References Appendix - IntelliJ Hints and Tips Shortcut Keys Code Completion Navigating Source Code Running a JUnit Test Loading Project Source Help Menu Summary Appendix - Exercise Answers Chapter Three - My First JUnit Test Chapter Four - Work With Other Classes Chapter Five - Work With Our Own Classes Chapter Six - Java Classes Revisited: Constructors, Fields, Getter & Setter Methods Chapter Eight - Selections and Decisions Chapter Nine - Arrays and For Loop Iteration Chapter Ten - Introducing Collections Chapter Eleven - Introducing Exceptions Chapter Twelve - Introducing Inheritance Chapter Thirteen - More Exceptions Chapter Fourteen - JUnit Explored Chapter Fifteen - Strings Revisited Chapter Sixteen - Random Data Chapter Seventeen - Dates & Times Chapter Eighteen - Properties and Property Files Chapter Nineteen - Files Chapter Twenty - Math and BigDecimal Chapter Twenty One - Collections Revisited Introduction This is an introductory text. At times it takes a tutorial approach and adopts step by step instructions 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 this book. 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 oriented around writing automation code to support testing, rather than writing applications. As such 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 for anyone 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 was unnecessarily 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 simple applications from the command line, then build up into more Java constructs and GUI applications. When I write Java, I rarely compile it to a standalone application, I spend a lot of time in the IDE, writing and running small checks and refactoring to abstraction layers. 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 not learn how to build and structure an application. That is useful knowledge, but it can be learned 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 a lot of additional libraries, since once you have the basics, picking up a library and learning how to use it becomes a matter of reading the documentation and sample code. Exclusions This is not a ‘comprehensive’ introduction. This is a ‘getting started’ guide. Even though I concentrate on core Java, there are still aspects of Java that I haven’t covered in detail, I have covered them ‘just enough’ to understand. e.g. inheritance, interfaces, enums, inner classes, etc. 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 of those 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 automation code 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 my testing, 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; I did not use those constructs with my early automation. I also want to keep the book small, and approachable, so that people actually read it and work 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 simply don’t cover any of the new functionality added in Java 1.8 because I want you to learn the basics, and start being productive quickly. After you complete this book, you should be able to pick up the new features in Java 1.8 when you need them. Supporting Source Code You can download the source code for this book from github.com. The source contains the examples and answers to exercises. I suggest you work through the book and give it your best shot before consulting the source code. github.com/eviltester/javaForTestersCode The source code has been organized into two high level source folders: main and test. The full significance of these will be explained in later chapters. But for now, the test folder contains all the JUnit tests that you see in this book. Each chapter has a package and beneath that an exercises and an examples folder: 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 the exercises in Chapter 3 This should make it easier for you to navigate the code base. And if you experience difficulties typing in any of the code then you can compare it with the actual code to support the book. To allow you to read the book without needing to have the source code open, I have added a lot of code in the body of the book and you can find much of the code for the exercises in the appendix. The Appendix “IntelliJ Hints and Tips” has information on loading the source and offers a reference section for helping you navigate and work with the source code in IntelliJ. About the Author Alan Richardson has worked as a Software professional since 1995 (although it feels longer). Primarily working with Software Testing, although he has written commercial software in C++, and a variety of other languages. Alan has a variety of on-line training courses, both free and commercial: “Selenium 2 WebDriver With Java” “Start Using Selenium WebDriver” “Technical Web Testing” You can find details of his other books, training courses, conference papers and slides, and videos, on his main company web site: CompendiumDev.co.uk Alan maintains a number of web sites: SeleniumSimplified.com : Web Automation using Selenium WebDriver EvilTester.com : Technical testing JavaForTesters.com : Java, aimed at software testers. JavaForTesters.com also acts as the support site for this book. Alan tweets using the handle @eviltester Acknowledgments This book was created as a “work in progress” on leanpub.com. My thanks go to everyone who bought the book in its early stages, this provided the continued motivation to create something that added value, and then spend the extra time needed to add polish and readability. Special thanks go to the following people who provided early and helpful feedback during the 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 to explain their code. You helped me observe what a good developer does and how they work. The fact that you were good, forced me to ‘up my game’ and improve both my coding and testing skills. 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. Chapter One - Basics of Java Revealed Chapter Summary An overview of Java code to set the scene: class is the basic building block a class has methods method names start with lowercase letters class names start with uppercase letters a JUnit test is a method annotated with @Test JUnit test methods can be run without creating an application In this first chapter I will show you Java code, and the language I use to describe it, with little explanation. I do this to provide you with some context. I want to wrap you in the language typically used to describe Java code. And I want to show you small sections of code in context. I don’t expect you to understand it yet. Just read the pages which follow, look at the code, soak it in, accept that it works, and is consistent. Then in later pages, I will explain the code constructs in more detail, you will write some code, and I’ll reinforce the explanations. Java Example Code Remember - just read the following section Just read the following section, and don’t worry if you don’t understand it all immediately. I explain it in later pages. I have emphasized text which I will explain later. So if you don’t understand what an emphasized word means, then don’t worry, you will in a few pages time. An empty class A class is the basic building block that we use to build our Java code base. All the code that we write to do stuff, we write inside a class. I have named this class AnEmptyClass. 1 package com.javafortesters.chap001basicsofjava.examples.classes; 2 3 public class AnEmptyClass { 4 } Just like your name, Class names start with an uppercase letter in Java. I’m using something called Camel Case to construct the names, instead of spaces to separate words, we write the first letter of each word in uppercase. The first line is the package that I added the class to. A package is like a directory on the 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 this class has a method called aMethodOnAClass which, when called, prints out "Hello World" to the console. 1 package com.javafortesters.chap001basicsofjava.examples.classes; 2 3 public class AClassWithAMethod { 4 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. A JUnit Test For the code in this book we will use JUnit. JUnit is a commonly used library which makes it easy for us to write and run Java code with assertions. A JUnit test is simply a method in a class which is annotated with @Test (i.e. we write @Test before the method declaration). 1 package com.javafortesters.chap014junit.examples; 2 3 import com.javafortesters.chap001basicsofjava.examples.classes.AClassWithAMethod; 4 import org.junit.Test; 5 6 public class ASysOutJunitTest { 7 8 @Test 9 public void canOutputHelloWorldToConsole(){ 10 AClassWithAMethod myClass = new AClassWithAMethod(); 11 myClass.aMethodOnAClass(); 12 } 13 } In the above code, I instantiate a variable of type AClassWithAMethod (which is the name I gave to the class earlier). I had to import the class and package before I could use it, and I did that as one of the first lines in the file. I can run this method from the IDE without creating a Java application because I have used JUnit and annotated the method with @Test. When I run this method then I will see the following text printed out to the Java console in my IDE: Hello World Summary I have thrown you into the deep end here; presenting you with a page of possible gobbledygook. And I did that to introduce you to a the Java Programming Language quickly. Java Programming Language Concepts: Class Method JUnit Annotation Package Variables Instantiate variables Type Import Programming Convention Concepts: Camel Case JUnit Tests are Java methods annotated with @Test Integrated Development Environment Concepts: Console Over the next few chapters, I’ll start to explain these concepts in more detail. Chapter Two - Install the Necessary Software 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. The tools you will install are: Java Development Kit Maven An Integrated Development Environment (IDE) You will also learn how to create your first project. When you finish this chapter you will be ready to start coding. I suggest you first, read this whole chapter, and then work through the chapter from the beginning and follow the steps listed. Introduction Programming requires you to setup a bunch of tools to allow you to work. For Java, this means you need to install: JDK - Java Development Kit IDE - Integrated Development Environment For this book we are also going to install: Maven - a dependency management and build tool Installing Maven adds an additional degree of complexity to the setup process, but trust me. It will make the whole process of building projects and taking your Java to the next level a lot easier. I have created a support page for installation, with videos and links to troubleshooting guides. JavaForTesters.com/install If you experience any problems that are not covered in this chapter, or on the support pages, then please let me know so I can try to help, or amend this chapter, and possibly add new resources to the support page. Do you already have JDK or Maven installed? Some of you may already have these tools installed with your machine. The first thing we should do is learn how to check if they a...
View Full Document

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture