Showing posts with label Unit Testing. Show all posts
Showing posts with label Unit Testing. Show all posts

Wednesday, June 15, 2016

AUTOMATION 7 - Unit Check, Part 3: summing up

We're looking at unit checking a Java dice rolling class - see our first in this series for more information.


Previously we were looking at testing random number distribution, which was a little complex.  Before we wrap up on unit testing, I have one more test to include before we look at summing up unit testing.

Anything else worth testing?

So far we've checked that each number 1-6 occurs when we define a 6 sided dice.  We've also checked over large data sets that each number comes up about 1/6 of the time within a tolerance.

Today's test is less obvious, simple, but really useful.  Do only the numbers 1-6 come up?  We want to check there's no occasional 0, 6 or anything else?

The way to do that is a modification of our test from yesterday - we'll run 600,000 times, and confirm all the values for 1, 2, 3, 4, 5 and 6 add up to 600,000.

 @Test public void noUnexpectedValues() {
...
int totalRolls = 600000; int grandTotal = 0; ... //Add each value to the grand total for(counter = 0; counter < numSides; counter++) { grandTotal += countArray[counter]; } //If this fails, there must be some values outside of range assertTrue("Some dice rolls must be outside 1-6 range", grandTotal == totalRolls ); }

Running that we get ....


JUnit is really happy with that - which is probably the simplest test we've done so far!

When it unit checking appropriate?

Yesterday we were running a check that used 600 million dice rolls.  Let me Bibically put that into perspective ...


In the Bible, it's said that soldiers at the feet of Jesus's crucification threw dice to divide up his possessions.  Let's suppose for a moment that Jesus cursed them (although it would throw out all Jesus's teachings if he was that kind of a guy) to stay there until they'd rolled their dice 600 million times.

Well, they'd be there, assuming a roll every 2 seconds (I'm a wargamer, I know how long dice take to roll), then they'd be there for 40 years.  With no sleep or toilet breaks.

But all this shows how in 2 seconds of unit testing we've achieved more than many years of real life experience.  Okay - now let's assume we wanted to do the same test with a GUI check system.  I know we've not really covered GUI checks yet.  But as I've said a limiting factor vs unit checks is screen refresh.

Let's say we're able to reduce the screen refresh problem down to even 0.01 seconds.  We're still looking at about 70 days to run the same test which it took 21 seconds on my machine.  And believe me, my machine isn't state of the art, but you're welcome to donate me a Macbook Pro if you want.

[Knowing my luck - that will mean I'll be spammed with "Apple are giving aware free Macbook Pros, click here to find out more]

What this does show though is how much faster unit checks can be than GUI checks.  If they're appropriate you can do checks which that are order of magnitudes faster than what you can achieve with GUI checks.

This leads back again to the third iron rule - we want always to make a check we want to run as simple as possible.  If we want to run a lot of checks in the volume we did previously, it makes sense to run them where they are simplest and fastest - in the unit check area,



But there's a drawback

How many of you testers out there can see what's in your developer's unit tests?  They're kind of squirreled away - you assume if it built, it must have passed, right?

We don't tend to make these things visible, but we should.  Because as we've shown they can be useful at checking an aspect of the system in depth, and to a volume that's ordinarily unfeasible.


Extension material

Ask around your current project about the unit tests used.  Can someone help you to see them?  Can you suggest some?

If you're following with Eclipse, try writing some similar tests for 8 or 20 sided dice.

If you want a real challenge, create a parent class which rolls multiple dice, and create some JUnit tests for that.

AUTOMATION 6 - Unit Check, Part 2: random distribution

We're looking at unit checking a Java dice rolling class - see last time for more information.


Previously by necessity we occasionally had to show some technical details, and raw Java code - I'm hoping those of you less technical are still with me.

Today will have less of that - I'll specify parts of code, so those of you experimenting with Eclipse yourselves can keep up and experiment, but it will be less important.

Distribution of numbers



Okay - I've got a test which assures me all the numbers 1-6 come up.  But that doesn't address my major concern, which is I'm worried that the number 1 will come up significantly less than numbers 2, 3, 4, 5 or 6.

How would I manually test this?  Well as before, I'd keep pressing "roll again" and keep a table of the results.  I'd expect them to look evenly spread, 1/6 each.  Ish.

Again - great test, but there's a clause there like above "I'd keep doing until I'm satisfied / dissatisfied".

Automation needs a hard and fast rule.  Welcome to the world of computers - things have to either be a 1 or a 0, a pass or a fail.  And "until I'm satisfied" is not hard or fast.

Now ... there's a something which is often quoted about random numbers.  If you sample over a large enough sample set, then you should see on your dice rolls a perfect split of 1/6 for each number using a 6 sided dice.

When I've manually tested this before (believe me I did statistics at University and I did this one night with my best friend David Farish), and notice that the results do smooth out a bit.  However I'd usually get bored at about 200 dice rolls.

However in my automated unit check, I have the power to sample over 6 million dice rolls.  Over such a huge number, everything should even off to a cool million each.  So I'm going to rename and reuse that code I had yesterday.


@Test public void randomNumberSpread() { System.out.println("Confirming even distribution"); int totalRolls = 6000000; ...

  //Confirm each number rolled 1/6 of the time for(counter = 0; counter < numSides; counter++) { assertTrue("Dice rolls for " + (counter+1) + " not perfect 1/6", (countArray[counter] == (totalRolls/6) ) ); }
}


Let's see how it works shall we?




Oh - that failed.  I thought over such a large number, it'd all even out.  When I ran this, I genuinely thought it might be within 1 or 2 of the target number.

Maybe I need to roll more.  Let's set our total rolls for 600 million, and see what happens?

It takes about 21 seconds to run, but ...

Maybe if I try again?



Well, obviously I've not run enough dice yet, let's set it to 60 billion!!!  And that dear readers is where I break my software completely because


Basically I've pushed the number of rolls so high, that Java can't handle unless I change a lot of the data types I'm using.

I could ... but I'm reminded of the third iron law,


And I'm starting to go down the path of making this check way too complex.  Just adding more dice rolls doesn't seem to help.

Here's the frustrating thing - look at the results from these three runs

Run 1


Run 2


Run 3


In Run 1, the dice rolls for numbers 1, 4 and 6 fall just under the 100 million "perfect" number.  In Run 2, the dice rolls for numbers 1 and 6 are just above 100 million.  Whilst on Run 3, the dice rolls for the number 4 is above 100 million.

Intuitively, using manual judgement, that says to me that I've seen numbers fall above and below the average, but only a little bit.  So that looks okay to me.

I've tried this test several times - sometimes it take 2 goes, sometimes 3, sometimes 4.  Fundamentally though the challenge is "how do I create a hard and fast rule for this to test?".

When I posed this problem on Twitter, Iain Mc pointed out to me


I tried to get a good calculated way to determine an expect deviation for this which led me to Yahoo answers and this ...

d^2 = [1/(N-1)]∑(xi - m)^2 = [1/(N-1)]*{∑[N*vi*P(vi)]^2 - 2*N*m*∑v*P(vi) +N*m^2}

d = √ [1/(N-1)]*{∑[N*vi*P(vi)]^2 - 2*N*m*∑vi*P(vi) +N*m^2}

At which point, I remembered that I've not done "hard maths" for a while, so maybe Iain had a point.

What I've decided to do is to modify the test.  Obviously running 600 million rolls doesn't superbly define the problem for me, and at 21 seconds, takes a bit too long.



What I've decided to do is to test a threshold of plus or minus 1%, which should be good enough.  And I'll do it over 600,000 dice rolls, which will be much faster (couple of seconds including compilation), but still nicely divisible by 6.



@Test public void randomNumberSpread() { System.out.println("Confirming even distribution"); int totalRolls = 600000; int minVal, maxVal;
...

//Work out min/max threshold as +/- 1%
minVal = (int) (0.99 * totalRolls / 6);
maxVal = (int) (1.01 * totalRolls / 6);

   //Confirm each number rolled 1/6 of the time for(counter = 0; counter < numSides; counter++) { assertTrue("Dice rolls for " + (counter+1) + " below threshold of " + minVal, (countArray[counter] > minVal ) ); assertTrue("Dice rolls for " + (counter+1) + " above threshold of " + maxVal, (countArray[counter] < maxVal ) ); }
}

And that seems to run nicely ... and so far repeatedly ...


Okay - that's a lot of maths and thinking.  We still have a little more to play with before we sum up, for now, we'll wrap up.

Recap

So we managed to create an important automated check - but it was a little harder than initially expected, because as the first iron law said, we needed to summarise what we wanted to check into a hard pass/fail criteria.  And that turned out to be harder than we intuitively first assumed.



Extension material

Have a think about what other tests you think might be worth running.  If you're using Eclipse, have a go with it.

But also try and think about problems with this for you as a tester.

Tuesday, June 14, 2016

AUTOMATION 5 - Unit Checks, Part 1: testing randomness

Warning - this example is going to contain some Java samples.  However, I don't want you to be put off that too much if you're not technical.  You should be able to follow the discussion and the outputs even if you're unfamiliar with code.


I love games - in fact so much so my son and I run a wargaming YouTube channel!

Most of the board/wargames we run rely on use dice to determine events - so a dice rolling application seems like something useful to build.

Below is a Java class I've written - don't worry if you can't read it, I'll explain the key features,

  • diceClass (int num) - it's called a constructor which creates a dice object with the number of sides (num) that I request
  • diceClass () - this is a default constructor.  If I don't specify a number, create a 6 sided dice, as they're the most common
  • rollDice() - this creates a random number as if the dice was rolled.  It can be any number between 1 and the number of sides the dice has.
  • returnDiceNumber() - I've used something called encapsulation here.  The number on the dice is private, which means it can't be accessed by anything outside of this code.  Instead I've provided a method which will return the currently rolled value on the dice!



import org.junit.Test; public class diceClass { private int numSides; // number of sides on the dice private int diceNumber; // the random number on the dice public diceClass (int num) { numSides = num; this.rollDice(); } public diceClass () { this(6); } public void rollDice() { diceNumber = 1 + (int)(Math.random() * numSides); } public int returnDiceNumber() { return diceNumber; } }


In layman's terms, I have code which will allow me to create a dice, roll it, find the value.  Pretty simple - but I still want to check it.  Because when I used to program using BASIC on the ZX Spectrum, I remember it was very easy to introduce a rounding error which would mean the first number would be less likely to be represented.

Right now I've not decided what checks to do, or even if it should be GUI or unit check.

Let's actually take a step back - if I was manually testing this what kind of test would I do?  Can I automate that?

Make sure every number comes up test

That seems pretty obvious - let's say the GUI for this looks like this ...


Hopefully it's pretty obvious - every time you hit "roll again" a new number comes up in the box, which currently says "4".

So what's a good test?  Well, I'd press "roll again" several times and expect a different result each time.  Actually random numbers don't work like that ... I'd expect a different number most times.

And I would expect to see the numbers 1-6 appear whilst doing it.

That is a really good first definition of a test.  However you're about to find the difference between a check and a test.  What you've just defined is far too ambiguous to become an automated check.

When we defined automation - it was a script driven set of controls for a system together with the determined outputs.  And that direction is missing.

As a manual tester, I'd run that until I was satisfied.  In an automated check, you have to define "satisfaction" as a hard number.

If I said "if I roll a 6-sided dice 6 times ... I expect to have seen the numbers 1, 2, 3, 4, 5 and 6 at least once" - that check is going to fail a lot.  Checks that fail a lot but don't find a true problem are bad, because they build up a lack of trust in the automation so that when something genuinely problematic occurs "we get fails all the time, but it doesn't matter".  But more on that later.



If I changed it to "if I roll a 6-sided dice 10 times ...  I expect to have seen the numbers 1, 2, 3, 4, 5 and 6 at least once", I expect to see the test fail less. But thanks to randomness, it's still possible to fail.

Let's actually define what that JUnit code would look like for a check with just 6 rolls

import org.junit.Test; import static org.junit.Assert.*; public class testDice { @Test public void everyNumberOccurs() { System.out.println("Confirming every number happens"); diceClass dice1 = new diceClass(); int numSides = 6; int[] countArray = new int[numSides]; int counter, index; int totalRolls = 6; //Roll the dice totalRolls times, count the results for(counter = 0; counter < totalRolls; counter++) { dice1.rollDice(); index = dice1.returnDiceNumber(); countArray[index-1]++; } //Rolling done, show us the numbers for(counter = 0; counter < numSides; counter++) { System.out.println("Assert: Number of " +
(counter+1) + " = " + countArray[counter]);
}

//Now confirm each is greater than 0
for(counter = 0; counter < numSides; counter++)
{
assertTrue("Did not find " +(counter+1)+ " rolled",
countArray[counter]>0);
}
} }

Okay - let's run that.  What's neat about JUnit checks, they run as part of the build process for code, so you get a response pretty quick!

On our first go, you can see in the Eclipse console that not every number has occurred ...


Let's give it another go ... close but no cigar ...


And over under the Eclipse Failure Trace, the assertTrue has generated a failure,


Obviously I'm going to have to sample over a large enough set to reduce the chance of an error.  So I'm going to use as the basis of my check "if I roll a 6-sided dice 100 times ...  I expect to have seen the numbers 1, 2, 3, 4, 5 and 6 at least once".  That's probably excessive - but I've no real clue how many I'd do before I gave up in frustration.  And the automation needs an iron rule.

I'm going to change the value of totalRolls to 100 in the code above.  That means sampling 100 dice rolls.  Let's see what happens now ...



This check runs almost instantaneously.

Now of course I could use my GUI automation here to run this, it'd be okay - but much slower.  I'd need to wait for a press of the button, screen refresh,  read the value from the field, store it.  Generally I find it seems to take about 0.1 seconds for a screen refresh (hey, we get slow internet in New Zealand), unless you have a cut down webpage.  So checking 100 dice rolls could take a few seconds.

According to our iron rule ...


It probably makes sense to use a unit test over a GUI test for such a mass action.  The developer certainly finds out about the problem much simpler - it comes out as part of the build process.




More next time

I'm going to leave it here for today - we're going to look at more example checks we can do, and think a bit deeper of how this compares to GUI tests.  But for today we'll leave it here before you get overwhelmed.


Extension material

You might want to have a play around with this yourself - you might want to install Java Eclipse on your machine.  But don't forget you will also need to install the Java JDK as well from Oracle.