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.

Tuesday, 19 July 2016

How to debug Java with IntelliJ: breakpoints, evaluate expression, watches and variable view

I have deliberately created a failing test. Obviously deliberately since I would never ever create such simple issues in code. I’m far too experienced for that. :)
Even though these issues were created deliberately I still need to know how to debug code. In this blog post I’ll describe how I debug Java using IntelliJ.



You can also 'watch' this post on youtube

 I have some code which fills a dynamic array with “*” to simulate a set of ‘pixels’ - whatever.
But it doesn’t work.
@Test
public void createSquare2dArray(){

    int squareWidth = 16;

    String[][]square = new String [squareWidth][];

    for(int row=0; row<square.length; row++){
        square[row] = new String[squareWidth];
        for(int i=0; i< (squareWidth+1); i++){
            square[row][i] = "*";
        }
    }
   
    print2DStringArrayIterators(square);
    System.out.println("");
}
It throws an error on the line
square[row][i] = "*";
Something about…
   java.lang.ArrayIndexOutOfBoundsException: 16
at com.javafortesters.chap009arraysiteration.exercises.
TriangleExercisesDebugTest.
createSquare2dArray(TriangleExercisesDebugTest.java:40)
It will be fairly obvious to most people what is going on but if I put a breakpoint on the line that is failing then I can Debug the @Test method and step through the code to see what is going on.


Oh look, a breakpoint.



Then run in debug mode.


When the test is running in debug and has stopped at a breakpoint, I can:
  • see all the current variables,
  • expand them when they are an object instance of some sort
  • resume execution (stop at next breakpoint)
  • step over the line to advance execution bit by bit
  • step into the code to advance execution, but into the method implementation
I can also highlight code and “Evaluate Expression”.

This lets me execute code on the fly and experiment with different code constructs.
e.g. I can evaluate square[row][i] note that this is not the full line, just ‘code’.
I can run that and experiment with it
e.g.
  • square[row][i] returns null because we haven’t set the value yet
  • square[row][15] also returns null because we haven’t set the value yet
  • square[row][16] reports java.lang.IndexOutOfBoundsException: Invalid array range: 16 to 16
That IndexOutOfBoundsException seems suspiciously close to the error I saw when I ran the test.
I could add a ‘Watch’ for i even though it is obvious in the Variables list by clicking the green + symbol in the ‘Watch’ section.


So if I step through until i==16 then I can also see in the variables list the exception will be thrown - even though the line hasn’t executed yet.

And we know the problem is that I copied the code from a previous ‘triangle exercise’
String[][]triangle = new String [16][];

for(int row=0; row<triangle.length; row++){
    triangle[row] = new String[row+1];
    for(int i=0; i< (row+1); i++){
        triangle[row][i] = "*";
    }
}
And accidentally left a +1 in the loop condition.
I fix that.
for(int row=0; row<square.length; row++){
    square[row] = new String[squareWidth];
    for(int i=0; i< squareWidth; i++){
        square[row][i] = "*";
    }
}
And then I have a problem in my next method.
Instead of printing out a 16x16 square of *
It prints out:
****************
And here is the horror in all its glory:
public void print2DStringArrayIterators(String [][]multi){

  Iterable<String[]> outerList = Arrays.asList(multi);
  Iterator<String[]> outer = outerList.iterator();

  while(outer.hasNext()){
    String[] innerMulti = outer.next();
    Iterable<String> innerList = Arrays.asList(innerMulti);
    Iterator<String> inner = innerList.iterator();

    while(inner.hasNext()){
       String pixel = inner.next();
       System.out.print(pixel);
    }
    System.out.println("");
    break;
  }
}
I decided to “get fancy” and use iterators and lists instead of just for loops with arrays.
But I didn’t get fancy enough. I should have wrapped my print2DStringArrayIterators with @Test methods and made sure it worked before I used it.

  • Me: “But it prints out, I couldn’t unit test it”
  • Other Me: "You could have written a method that returned the output, and we could have used @Test to assert on its functionality
  • Me: … 
  • Other Me: Yeah, exactly.

But I didn’t do that. So I have to debug it instead.
If I breakpoint the line where the method is called:
print2DStringArrayIterators(square);
Then I can “step into” the method and debug from there.
And As I step through the method, the problem is obvious - the break; that I added by mistake.

Summary

OK. So these were pretty poor examples, but, they are also very similar to code examples that I’ve received emails from, and probably wrote myself back in the day (Monday, or yesterday, or something).
Basics:
  • Yes we prefer to TDD our code
  • if we don’t TDD we better learn how to debug
  • use breakpoints
  • step through code
  • use the ‘variables view’
  • setup up ‘Watches’ if you have a lot of variables
  • use ‘Evaluate Expression’ to experiment in the running code
  • use Resume to run to next breakpoint
  • use Step Into to move to the next level of code in a method
Try it and see.

Thursday, 2 June 2016

Does dependency between test execution imply lack of abstraction layers?

TLDR; I try to write tests at an appropriate semantic level so I never need to create dependencies between @Test methods, I re-use abstraction calls instead of dependencies between @Test methods.

People often email me the question “How do I make a test run after another test?”
I ask “Why do you want to do that?”
“Because I have a test that creates a user, then I want to use that user in another test.”
I generally answer “Don’t do that. Write some abstraction code to ‘create a user’ then use that in your ‘create a user test’ and in your ‘another test’.”
In the examples below I have made up an API for HTTP requests.

API Abstraction vs HTTP Direct with Test Dependencies

So instead of:
@Test
public void canCreateAUser(){

     // Send request to create a user
     Response r =
        myHttpLibrary.post("http://myurl/api/users").
                      withFormContent(
                      new Form().with().
                        field("username","bob").
                        field("password","dobbspass").
                        field("email","bob@mailinator.com").
                        .urlencoded()
                      );
                                   
                         
     Assert.assertEquals(201, r.statusCode);
     
     // URL to access created user is in location header
     // e.g. "http://myurl/api/user/12"
     String userURL = r.getHeader("location");                         

     // get the user and check created properly
     Response u = myHttpLibrary.get(userURL);

     Assert.assertEquals(200, userURL.statusCode);

     Assert.assertEquals("bob",
                         u.parseJson("user.username"));
     Assert.assertEquals("bob@mailinator.com",
                         u.parseJson("user.email"));
}

@Test
public void canAmendAUser(){

     // write the code that amends user
     // created in the test canCreateAUser
}
I would be more likely to write code that looks like the following:

@Test
public void canCreateAUser(){

     Response r = myApi.createUser("bob",
                                   "dobbspass",
                                   "bob@mailinator.com);
    
     Assert.assertEquals(201, r.statusCode);
     
     String userId = ResponseParser.getCreatedUserId(r);

     Response u = myApi.getUser(userId);

     Assert.assertEquals(200, userURL.statusCode);

     Assert.assertEquals("bob",
                         u.parseJson("user.username"));
     Assert.assertEquals("bob@mailinator.com",
                         u.parseJson("user.email"));
}

@Test
public void canAmendAUser(){

     Response r = myApi.createUser("bob",
                                   "dobbspass",
                                   "bob@mailinator.com);
    
     Assert.assertEquals(201, r.statusCode);
     String userId = ResponseParser.getCreatedUserId(r);

     Response a = myApi.amendUser(userId,
                                  "email","newbob@mailinator.com");

     Assert.assertEquals(200, userURL.statusCode);
     
     Response u = myApi.getUser(userId);

     Assert.assertEquals(200, userURL.statusCode);
     Assert.assertEquals("bob@mailinator.com",
                         u.parseJson("user.email"));
}

Again - I’ve made up the API, so it isn’t ‘real’ code, so it might have syntax errors, and it will not work if you try to use it.
But it illustrates the creation of an abstraction layer to access the API which you can re-use, rather than trying to use the @Test method as an abstraction layer.
For me this builds on a quote from Dijkstra from "The Humble Programmer"
“…the purpose of abstracting is not to be vague, but to create a new semantic level in which one can be absolutely precise.”
@Test methods are an attempt to abstract a small set of preconditions, actions and assert on a subset of postconditions to justify the title of the @Test method.
We wouldn’t want to reuse ‘canCreateAUser’ we want to re-use ‘create a user’. We don’t need all the additional assertions in the ‘canCreateAUser’ when we ‘create a User’. We only need those additional assertions when we test the process of creating a user rather than when we create a user for use with other actions.

Why would people avoid creating abstractions?

Since I don’t avoid creating abstractions, I have to ‘suspect’ why people might not code like this. And remember the above is an example of an approach, not an example of ‘great code that you should follow’. There are many ways to implement an abstraction layer around an Api to support re-use and made your @Test code readable and maintainable. This was a first attempt that I thought illustrated the point, and remained readable with only one extra layer of semantics.
Possible reasons:
  • I want to avoid repeating code
  • I don’t want to hide the implementation of calling the API
I’m sure other reasons exist - feel free to comment if you have experience of a good reason, or comment with a link to an alternative experience report.

I want to re-use @Test methods to avoid repeating code

The main code we are trying to avoid repeating is:
     Response r =
        myHttpLibrary.post("http://myurl/api/users").
                      withFormContent(
                      new Form().with().
                        field("username","bob").
                        field("password","dobbspass").
                        field("email","bob@mailinator.com").
                        .urlencoded()
                      );
I don’t think increasing the coupling and dependency between tests worth avoiding the repeated code since I can avoid repeating the code by moving it to an API class. And as a side-effect my @Test method concentrates on the assertion of postconditions rather than the actions.
One other strategy that ‘avoid repeating code’ (while also avoiding abstraction layers) creates is ‘large @Test methods’
Which might mean:
@Test
public void canCreateAmendAndDeleteAUser(){

     // insert lots of direct API
     //        calls and assertions to
     // create a user
     // assert on the users creation
     //        for all post conditions related to create
     // amend the user
     // assert on the users amendment
     //        for all post conditions related to amendment
     // delete the user
     // assert on the users deletion
     //        for all post conditions related to deletion
}
Note, I removed the code because it would be too long, so imagine what the code would be extrapolating from the first example with the myHttpLibrary.
i.e.
  • a single test instead of multiple tests for ‘create’ ‘amendment’ and ‘deletion’
  • if this ‘single’ test fails I don’t know if it was the ‘creation’ or ‘amendment’ or ‘deletion’ by reading test names I have to debug the long test
Instead of an equivalent test using abstractions:
@Test
public void canDeleteAUserAfterAmendment(){

     Response r = myApi.createUser("bob",
                                   "dobbspass",
                                   "bob@mailinator.com);    
     Assert.assertEquals(201, r.statusCode);

     String userId = ResponseParser.getCreatedUserId(r);

     Response a = myApi.amendUser(userId,
                                  "email","newbob@mailinator.com");
     Assert.assertEquals(200, userURL.statusCode);
     
     Response d = myApi.deleteUser(userId);
     Assert.assertEquals(200, userURL.statusCode);

     Response d = myApi.getUser(userId);
     Assert.assertEquals(404, userURL.statusCode);

}
  • In the ‘abstraction’ example, I only assert on the minimum postconditions necessary during the execution i.e. the status codes
  • because I have other tests which check ‘creation’ and assert on more postconditions in the creation and I have other tests which check ‘amendment’ and assert on more postconditions in the amendment, so if there is a problem with ‘creation’ I would expect a ‘creation’ test to fail rather than have to debug a ‘canCreateAmendAndDelete’ @Test
  • I have minimal repeated code because I’m using an abstraction layer
  • I don’t need as many comments because the code is readable

I don’t want to hide the implementation of calling the API

What semantic level is the @Test working at?
Sometimes I have an API abstraction layer which I use for most @Testmethods because I’m not ‘testing’ that specific API call, I’m using it.
  • I might be testing a flow through the system
  • I might be testing the response, not the call
The following code is not at an API semantic level, it is at an HTTP semantic level:
     Response r =
        myHttpLibrary.post("http://myurl/api/users").
                      withFormContent(
                      new Form().with().
                        field("username","bob").
                        field("password","dobbspass").
                        field("email","bob@mailinator.com").
                        .urlencoded()
                      );
Therefore if we are testing the HTTP semantics of the API then this is an appropriate level e.g.:
  • what happens if I add extra headers?
  • what happens if my form fields are in a different order?
  • what happens if it is a PUT instead of a POST
  • etc.

Summary

It never occurs to me to try to make @Test methods dependent on each other.
I generally refactor to abstraction layers very quickly to ensure my @Test methods are written at the semantic level necessary for that @Test.
I combine multiple layers of abstraction to make the semantics in the @Test clear.
I suspect that, if you want to make your @Test methods run in a specific order, or make your @Test methods dependent on other @Test methods, you may not have the correct level of abstraction and are using ‘dependency’ as a mechanism to solve a problem that ‘refactoring to abstraction class’ might solve as quickly, and with more benefit.
Benefits:
  • Don’t worry about dependencies
  • Readable code
  • Easy to maintain when the API changes
  • @Test are not dependent on an HTTP library so you can use different libraries if necessary
  • Re-use the API abstractions for different types of testing - functional, integration, exploratory, performance
  • Fewer issues with parallel execution of @Test code

Thursday, 21 April 2016

Source Code for House Of Test Java Technical Testing Case Study Videos Released

I have released the source code github.com/eviltester/houseOfTestDataGenCaseStudy for my Java Technical Testing Video Case Study
There isn’t too much to the source code. A single @Test method in an Test .java file.
The pom.xml was really just to create a basic project in IntelliJ to use the inbuilt IntelliJ decompiler.
The source code is the code used to ‘test’ the random generation. This won’t work unless you add the data generation tool as a dependent jar as described in the case study videos.
And I haven’t done any work to tidy up the code so again it reflects a ‘write whatever code you need to get the job done’ attitude.
If I use the code more than once then I would revisit it, refactor it, etc. etc.
But I didn’t. I used it during the case study and now it lives on github.
You can find more details about the case study in this blog post

Thursday, 14 April 2016

An example of creating a 'tool' using @Test methods without building a Java application

I previously mentioned that “Java For Testers” teaches Java without writing main methods, and in fact uses @Test annotated methods for all of its code.
I write tools like that, certainly for short lived tools that I might otherwise have to use a scripting language, or MVPs to try things out.
It is only after I have the basic MVP code, and then demonstrate the re-use value of the code (i.e. I re-use it enough to justify a GUI or command line interface) that I add a main method. I do explain main methods over here.
In this post I’m going to give a quick example of what an MVP tool in an @Test method looks like.
(skip to the bottom of the post if you want to watch a video of the approach in action.)



A few caveats before I start though:
  • I am not putting this forward as ‘good’ code. It has taken me longer to write this blog post than it did to write the code.
  • The code was designed to meet an immediate need
  • I didn’t TDD this code. I wrote an MVP to solve a problem and I was reviewing, checking, running and testing as I went.
    • with an MVP I often only add additional @Test methods when I refactor it and convert it for ongoing re-use
  • I noticed a few extra methods on the Files, File classes as I was building the code, so I experimented with those as I wrote the code, hence the mix of 1.5-1.8 code.
Since this was an MVP. I have a very specific task in mind. I’ll explain my usecase:
  • I write my ‘books’ using leanpub
  • I write a lot of my ongoing documentation in markdown generally
  • I use online services like dillinger.io to format my local markdown into a pdf
  • I use pandoc to create pdfs locally - particularly for client and consultancy reports
  • I want the ability to switch between the leanpub tools and local markdown->pdf tools
  • leanpub uses a Book.txt to create a list of files that it will process in sequence and convert into a book
  • dillinger.io and pandoc prefer to work from a single file
I want to write a document ‘as though’ it were a leanpub document, with Book.txt, but have the ability to create a pdf locally.
All I really need to do that is to combine all the files listed in the Book.txt file into a new leanpubpreview.md file. And then process the new leanpubpreview.md file in dillinger.io or pandoc.
I had a quick look on github to see if any other ‘tools’ had already been created for this purpose.
I found:
Both of these are written in scripting languages (ruby, python).
I thought that I’d knock up something simple in Java rather than install Python or Ruby to try these scripts.
Since this was an MVP:
  • I created a Java class called LeanPubPandocPreviewTest
  • I first wrote down my basic functional flow as a series of comments in a Java class.
// for given a hardcoded path to a Book.txt
// read the Book.txt file
// create a list of File names from Book.txt
// create a folder called pandoced (if necessary)
// create a new file in pandoced called leanpubpreview.md
// write all the contents of the files from Book.txt into this file
// output the command to generate the book to console

// note: this won't handle files with images at the moment

You can also see that I made a note of the limits of my experiment i.e. what it won’t do.
I then created an @Test method to act as my GUI.

@Test
public void createPreviewMVP() throws IOException {

I then worked through each comment in my requirement spec and wrote the code for it.
e.g.

// for given a hardcoded path
String book_txt = "D:\\temp\\manuscript\\Book.txt";

// read the Book.txt file
File book_txt_file = new File(book_txt);

if(!book_txt_file.exists()){
    throw new FileNotFoundException("Could not find file:" 
                           + book_txt_file.getAbsolutePath());
}

// create a list of File names from Book.txt
// experiment with the Java 1.8 readAllLines method
List<String> lines = Files.readAllLines(Paths.get(book_txt));

File book_txt_parent_folder = book_txt_file.getParentFile();

(You can see the rest of my adhoc code over on https://github.com/eviltester/pandocifier)
But…
  • It’s not pretty.
  • It’s not going to live long in that format.
  • The use of comments suggests, at a minimum, that the code should be moved into methods.
But…
  • it’s for me,
  • to do a thing that I need done now, and fast.
Since I didn’t use TDD, the ‘test strategy’ adopted was ‘build & check’. At the point that I wrote code that implemented each ‘comment’, I ran the @Test method in debug mode to check it was doing what I expected it to.
I didn’t spend a lot of time working out the ‘best’ way to implement the comment. I just wrote the ‘first’ code that worked well enough.
This approach got me to the bottom of the requirement list, with code that did the job, and an output file that I could process via pandoc to ‘preview’ a ‘leanpub’ project.
pandoc leanpubpreview.md -f markdown -s -o leanpubpreview.pdf --toc
I don’t normally release these type of MVP or adhoc tools to github. I normally have them on my local or xp-dev hosted repos.
But, for you, I’ve added this to Github so that you can see an example of using @Testmethods to create short lived, adhoc ‘tools’.
And if I do continue to use this tool, and refactor it to make it live longer, then you’ll be able to see the evolution of the code on github.
The github repo is https://github.com/eviltester/pandocifier
PS. this blog post was drafted using Markdown, written in Evernote, and converted to HTML using dillinger.io and pasted into blogger.com