Friday, 17 March 2017

Mistakes using Java main and examples of coding without main

TL;DR A potentially contentious post where I describe how I've survived without writing a lot of Java main methods, and how learning from code that is often driven by a main method has not helped some people. I do not argue for not learning how to write main methods. I do not argue against main methods. I argue for learning them later, after you know how to code Java. I argue for learning how to use test runners and built in features of maven or other build tools to execute your @Test code.


Monday, 5 December 2016

Let's Code - Binary Chopifier - Just Enough Code and Tooling to Start

TLDR; “Let’s code a Binary Chopifier” which I plan, code as prototype to plan in an @Test method, test interactively, experiment, and release as an @Test.




I want to create a few more examples of “Java in Action” and I’m doing that in some YouTube videos and blog posts that I think of as “Let’s Code”. First up is “Let’s code a Binary Chopifier” which I plan, prototype to plan, test interactively, experiment, and release to Github.

Let’s code a Binary Chopifier



When I was recording - Let’s Explore Google Search I made a note to write a binary chopifier.

https://www.youtube.com/watch?v=b3izXqERlqo

In this series of videos we are going to create the binary chopifier and add it to Test Tool Hub.

Plan

First thing I did was make notes on what I wanted to support me in testing:

    Tool idea: binary chopper!
    start: 1024 end: 2048
    result

    chop: value (inc)
-------------------
        01: 1536  (512)
        02: 1792 (256)
        03: 1920 (128)
        04: 1984 (64)
        05: 2016 (32)
        06: 2032 (16)
        07: 2040 (8)
        08: 2044 (4)
        09: 2046 (2)
        10: 2047 (1)
        11: 2048 (0)

Explaining Binary Chop:
  • I try a value of length 2048
  • System doesn’t accept it because it is too long
  • I want to find the limit
  • I try 1024 (I binary chop 2048) and if that is accepted then
  • I try 1536 (midway between 1024 and 2048), and if that is accepted then
  • etc. until I narrow down on the value that is the limit
And if you watch the video you’ll see my mental arithmetic process was quite slow. I could spend the time boosting my mental arithmetic, or I could write a tool to help me.

Guess which is easier?

So I write a tool.

Thinking through an algorithm

The plan above represents a basic output to support me as the tester.

Really all I want is the chop and the value, but I used inc to help me calculate the chops
  • So I calculate the difference between the start and end: 1024
  • Divide it by 2 (chop) to get 512 then I add that to start (inc) and get 1536
  • And keep going.

Start by writing a ‘@Test’ which does this

I start by writing an @Test method which implements this algorithm and I can see if it works or not

@Test
public void calculateBinaryChopForStartAndEndFromThoughtAlgorithm(){

  int start = 1024;
  int end = 2048;
  int choppoint=start;
  int inc = start;

  while(inc > 0){

  inc = (end-choppoint)/2;
  choppoint=choppoint+inc;
  System.out.println(String.format("%d (%d)", choppoint, inc));
  }

}

Which gives me the output

1536 (512)
1792 (256)
1920 (128)
1984 (64)
2016 (32)
2032 (16)
2040 (8)
2044 (4)
2046 (2)
2047 (1)
2047 (0)

Which isn’t what I was looking for, but makes sense since on the last increment it is zero.
Perhaps then, inc isn’t inc it is diff between end and chop point.

So rather than ‘add to’ the start, I should ‘take away’ from the end

    @Test
    public void calculateBinaryChopForStartAndEnd(){

        int start = 1024;
        int end = 2048;
        int choppoint=start;
        int inc = start;

        while(inc > 0){

            inc = (end-choppoint)/2;
            choppoint=end-inc;
            System.out.println(String.format("%d (%d)", choppoint, inc));
        }

    }

Which gives me my original plan:

1536 (512)
1792 (256)
1920 (128)
1984 (64)
2016 (32)
2032 (16)
2040 (8)
2044 (4)
2046 (2)
2047 (1)
2048 (0)

But since I’m working from the end, I’m wondering if what I actually do is just keep halfing the difference:

@Test
public void calculateBinaryChopForStartAndEndHalfDifference(){

  int start = 1024;
  int end = 2048;
  int diff = end-start;

  while(diff > 0){
  diff = diff/2;
  System.out.println(String.format("%d (%d)", end-diff, diff));
  }
}

Which gives me:

1536 (512)
1792 (256)
1920 (128)
1984 (64)
2016 (32)
2032 (16)
2040 (8)
2044 (4)
2046 (2)
2047 (1)
2048 (0)

And is much simpler.

And since this ‘test’ is a useful ‘tool’ for me - I’ll stop there for this video. And next I’ll start refactoring this out into a library for binary chopping so that I can then use that in the Test Tool Hub.


Friday, 21 October 2016

How to create and release a jar to maven central

TLDR; The instructions on apache and sonatype site are pretty good to help get library released to maven central. But you’ll need to learn about pgp signing and might need more rigour in your pom file. A fairly painless learning process that I recommend you go through and release something to the world.




I spend most of my time with Java writing stand alone applications to support testing or code that we run as part of CI. I haven’t had to create a library that I make accessible to other people through maven central.

I thought it was about time I did so.

In this post I’ll describe what I did and how I got a .jar in Maven Central.

What is the Library?

As part of my Selenium WebDriver online training course I created a ‘driver manager’ to allow code to more easily run across different browsers.
It works fine for the context of my course.
Over time I’ve started splitting the course source into multiple parts:
And I’ve had to copy the Driver.java into the continuous integration project.
I decided to pull it out into a separate library and make it accessible via maven central, that way it will be easier for people taking the course to use the Driver class in their own code.
And I can start maintaining it as a project on its own merits with better code and better flexibility, rather than something that just supports the course.

Summary of what to do?

What follows is a ‘checklist’ created from my notes about how I released.
Now that I have a groupid that will synchronise to maven central, it should be a simpler process if I want to create any future libraries.

A bit more detail

The documentation I linked to is pretty good. I mostly just copied the information from there.
And you can see the results in the released library code:
And the sample project that uses the library:

Changed my code to use minimal libraries

One change I made to the library pom.xml that is different from my normal use of the code in projects.
I decided not to include the full version of Selenium WebDriver - which I normally do when I use it:
i.e.
<dependency>
   <groupId>org.seleniumhq.selenium</groupId>
   <artifactId>selenium-server</artifactId>
   <version>3.0.1</version>
</dependency>
Instead I wanted the minimum I could add, since I know that the projects using it will be incorporating the full version of Selenium WebDriver.
So I just used the Java Interface:
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.0.1</version>
</dependency>

Configuring repositories in the pom.xml

I haven’t had to do this for a long time. I vaguely remember doing this in the past as a workaround for some local issue we had.
In order to access the -SNAPSHOT release version of the library I have to have the repository configured in my pom.xml
<!-- to use snapshot versionsof the driver manager we need to use the OSS nexus repo -->

<repositories>
    <repository>
        <id>osshr</id>
        <name>OSSHR Staging</name>
        <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </repository>
</repositories>
I imagine that this might prove a useful workaround if I ever encounter a site that has configured the maven config via settings that we are unable to access easily.

Deploy was easier than I thought

I haven’t used the release deploy in maven before. And the instructions had a whole bunch of commands:
//perform a release deployment to OSSRH with

mvn release:clean release:prepare

//by answering the prompts for versions and tags, followed by

mvn release:perform
But in the end I didn’t have to do this.
I changed the version to remove -SNAPSHOT and it ‘released’ when I did a mvn clean deploy

Tagging a release on Github

I haven’t ‘released’ on Github before so I created a release via the github GUI on the releases page

Gotchas

What went wrong?

I tried to use a groupid that I don’t own

I’ve been pretty laissez-faire with my groupids in my projects and high level package names because I’ve never released one before.
But to use maven central you need to have a domain that you own.
And someone has snapped up the .com that I often use in my code, so I needed to use the .co.uk that I own.
I might well start changing the code that I create to use this new groupid now :)

I put my group id the wrong way round

I tried mvn clean deploy for a snapshot release and I received:
[ERROR] Failed to execute goal org.sonatype.plugins:nexus-staging-maven-plugin:
1.6.7:deploy (injected-nexus-deploy) on project selenium-driver-manager:
Failed to deploy artifacts: Could not transfer artifact co.uk.compendiumdev
:selenium-driver-manager:jar.asc:javadoc:3.0.1-20161020.083347-1 from/to
ossrh (https://oss.sonatype.org/content/repositories/snapshots):
Access denied to: https://oss.sonatype.org/content/repositories/snapshots/co/uk/
compendiumdev/selenium-driver-manager/3.0.1-SNAPSHOT/
selenium-driver-manager-3.0.1-20161020.083347-1-javadoc.jar.asc,
ReasonPhrase: Forbidden. -> [Help 1]
I checked that my credentials were correct by logging into the oss nexus system
My issue was that instead of using groupid
  • uk.co.compendiumdev
I mistakenly used:
  • co.uk.compendiumdev
So don’t do that.

I forgot to release the gpg key

I forgot to release the gpg key when I created it, so I ended up trying to do a final release and seeing the following error during mvn clean deploy
[ERROR]     * No public key: Key with id: (xxxxxxxxxxxxx) was not
able to be located on
&lt;a href=http://pool.sks-keyservers.net:11371/&gt;http://pool.sks-keyservers.net:11371/&lt;/a&gt;.
Upload your public key and try the operation again.
Make sure you do this early in the process.
Also I had to wait 10 - 20 minutes before it was accessible.
To check, visit the site you uploaded to and then search for the key.
I had to search for the key id with 0x in front of it i.e.
  • 0x740585A4
  • and not 740585A4
http://pool.sks-keyservers.net/pks/lookup?search=0x740585A4
When it was available from the search, then I could mvn clean deploy

Future work

I still have a lot to learn here.
As a beginner:
  • I’ve added a lot of ‘stuff’ to the pom.xml that I don’t fully understand and need to research
  • I’m sure I’m taggging the release on Github inefficiently
  • I’ve only done one release so I’m not sure if it is fully setup yet
  • I do this manually and haven’t added a CI deploy - when I do I’ll read the sonatype blog post more carefully
And I have an actual todo list:
  • I need to document the library and example in more detail if I want usage to spread beyond my course.
  • I need to amend my wdci and course code to use the library
But, it was a lot less daunting than I expected and the documentation was pretty clear, and the OSSHR team were very helpful in getting me setup, I was very impressed given that the oss staging repositories and syncing to maven central is a free service.
Hope that helps someone on the road to making their release. All in all it was a good learning experience.

References

Wednesday, 5 October 2016

New Java For Testers Install Videos and Checklist for Windows and Mac Released

TLDR; use the startUsingJavaJunit checklist on github to install Java JDK, and Maven, it also has links to ‘install tutorial’ videos for Windows and Mac



One of the hardest parts of writing a book, is keeping it up to date.

Particularly for install instructions.

Its one of the reasons, that Java For Testers has a checklist approach to the install instructions in the book. And why I have information on the JavaForTesters.com website describing the install.

New Install Instructions

I have just updated the install instructions and videos online because:
  • Maven 3.3.9 has a slightly different install process (no need to create an M2_HOME environment variable, although nothing bad happens if you do, so the old instructions still work)
  • Mac, while ‘easy to use’, forces you to use the command line when installing development tools and people new to programming and command line find this hard - so the install instructions for Mac that I have on the web site, now use Homebrew.
  • IntelliJ GUI has changed enough, since the last time, I created the video that I receive questions on how to import projects
The install instructions are now supported by a Github project:
with an install checklist:
The project is basically a maven project with a single test, so when you run it, you can see that maven, and JDK are working on your machine.
I have install videos for both Windows and Mac:

Tuesday, 27 September 2016

How to fix IntelliJ issues by looking in the IntelliJ log

TLDR; View the IntelliJ log Help -> ‘Show Log in Explorer’


I experienced an issue when importing maven projects.

I found the answer to my problem on StackOverflow:
“…set Settings > Build, Execution, Deployment > Build Tools > Maven > Importing > JDK for Importer to Use JAVA_HOME…”
The above solution worked for me. But it made me realise that it is harder than it needs to be to find what is going wrong with IntelliJ if you don’t know one trick - how to view the logs with IntelliJ.

Monday, 8 August 2016

How to convert a breakpoint into a conditional breakpoint in IntelliJ

TLDR; right click on a breakpoint and add code that returns a boolean to make it a conditional breakpoint

Breakpoints are great. You find the section of code that you want to investigate. Click on the side of the screen to create a breakpoint. Run the code in debug and it stops where you want it.

But what if you only wanted to stop on that breakpoint sometimes.

What do you do?

Add a watch, then when the code stops at the breakpoint, look at the watch and if it is not what you want, carry on?

Well that’s one way.

The other way is a conditional breakpoint.

A breakpoint that only triggers when a certain condition is set.

Let’s have a look.

I have this test.


And it fails!

java.lang.ArrayIndexOutOfBoundsException: 16

    at com.javafortesters.chap009arraysiteration.exercises.
TriangleSquareExercisesDebugTest.createSquare2dArray
(TriangleSquareExercisesDebugTest.java:37)

well, it fails on something when it is 16.

Is it i==16 or is it row==16?

I know. I’ll convert the breakpoint to a conditional breakpoint and find out.

To create a conditional breakpoint I simply right click on the breakpoint symbol and type in a condition.

The condition is any adhoc Java code that will compile in the context of the breakpoint, and return a Boolean.

So I could make the ‘Condition’ i==15 then the breakpoint should only trigger when i equals 15.



Now when the breakpoint fires, I only have to step over once to get to the point where my code throws its error.

Rather than having to step through the loop 15 times.

Worth trying?

Tuesday, 2 August 2016

Is JUnit only for unit testing? What about system testing or UAT?

TLDR; We can use JUnit to execute code to support any type of testing.

Question:

Hi, you use Junit in the book “Java For Testers” and I thought JUnit was used for “unit testing” and “unit testing” was performed by developers , not testers. Is the purpose to learn JUnit and “unit testing” or other types of testing as well? In other words, would you recommend learning “java for Testers” to software testers who would rather not be involved in “unit testing” but rather involved in “system and UAT”?

Q: Is JUnit just for Unit Testing or can we use it for other testing as well? from Alan Richardson on Vimeo.


Answer:

JUnit is used for unit testing. And it is used for other types of testing as well.

I don’t think of JUnit as a Unit Testing Tool. Instead, I view it as a way of running code marked as ‘runnable by JUnit’. That code is marked by @Test annotations and is often called a Test, and those ‘Tests’ are often used for Unit testing, but they don’t have to be.

JUnit can be used as a test runner for any kind of test: e.g. system and integration tests; tests which are interacting with a deployed application.

e.g. the WebDriver tests here all use JUnit github.com/eviltester/webDriverExperiments and they interact with an application which runs in a browser.

And you can see me use JUnit it here to aid my interactive exploratory and system testing of an API:
The name JUnit should not lead you to think that it is only for Unit testing.

If you want to automate, from code, then you’ll need some way of executing the code. In the book we use JUnit as Test Runner to execute code.

I see a lot of examples of “how to learn Java” which use ‘main’ methods to allow execution of the code.

‘main’ methods are a good approach if you want to compile your code into an application.

Unfortunately I’ve seen that when people learn to write Java this way, they often have multiple ‘main’ methods in their code, without really knowing why a ‘main’ method is are used. And they don’t learn any strategies for running bits of code in an adhoc fashion, as well as a strategic fashion.

In the book “Java For Testers” I wanted people to learn Test Driven Development, but not make it a ‘thing’ just a natural process, so all the execution capabilities of the code are provided by @Test annotation, and executed from JUnit. This allows us to:
  • Tactically Run arbitrary code without create main methods or packaging the app
  • Use any library, not just for Unit testing, but also for Testing that integrates with deployed applications e.g. Web or API
  • Strategically create suites which we can use longer term
  • Unit test the abstraction layers and support code that we write so that we do Unit test, our System and Integration test code
  • Easily add our code into a continuous integration approach
Hopefully as you work through the book that will all become clearer.

If you want to automate, you will need to write code, and you’ll want to unit test that code as well, and you’ll use JUnit for that, as well as using JUnit to provide the ability to execute your code.

I rarely unit test the applications I work on as a tester, but I do unit test the code I write to automate those applications as part of my testing.

Hope that makes sense.

P.S. I think you are unlikely to strategically automate as part of a UAT process. But you might tactically automate (adhoc) data setup and configuration, and you’ll need coding skills to do that effectively.