To celebrate having reached the half-way point (hopefully), I went into town last week for my annual trip to the Design Museum, accompanied by some of my relatives.
It was a nice, bright shiny day in Old London Town:
The Design of the Year exhibition was on and there was a mix of the practical and strange:
On the left is a wall calendar made of Lego and, on the right, a giant-sized Twitter feed printer. There were cars and smartphone apps and chairs and dresses. There was also a rather nice, if expensive, folding bike:
and a new type of aircraft, similar to the Westland Pterodactyls of the 1930's:
More mundane, but perhaps just as significant, is Fairphone, from Holland. As the name implies, it's an ethically sourced smartphone.
... about programming, growing up in the 1970's and 80's, games, science fiction, working in a charity book shop, films, spending too much time watching television, living in Basildon and Essex, and whatever else emerges from my fevered imagination. If you're reading this, it's your fault you clicked on the link: I am not responsible for your actions.
Thursday, 31 July 2014
Saturday, 19 July 2014
True Detective
True Detective is now out on DVD in the U.K. Louisiana State Detectives Rust Cohle (Matthew McConaughey) and Marty Hart (Woody Harrelson) are called to the scene of what looks like a ritual murder:
The series follows the case in flashback as the two detectives are interviewed many years after by their counterparts working a similar murder. A lot of fuss has been made of the series, preempting a cult following, but it is justified. McConaughey is hot property at the moment, after Mud and more recent films, and Cohle is a very suitable vehicle. Some of the weirder ideas that Cohle has (or purports to have: you're never quite sure if he's just playing games) would sound rubbish from a lesser actor, but he holds the attention perfectly. Harrelson's role is more solid and conventional, but it contrasts well with Cohle and is no less compelling. I honestly believe that you could just show the interviews without the flashback and it would still be good watching.
The direction and script are equally good and a third component, even a third actor really, is the atmospheric Louisiana countryside, part industrial (a strong feature being the refineries and chemical works supporting oil industry along the Gulf coast) and still very rural and religious.
Very, very recommended.
The series follows the case in flashback as the two detectives are interviewed many years after by their counterparts working a similar murder. A lot of fuss has been made of the series, preempting a cult following, but it is justified. McConaughey is hot property at the moment, after Mud and more recent films, and Cohle is a very suitable vehicle. Some of the weirder ideas that Cohle has (or purports to have: you're never quite sure if he's just playing games) would sound rubbish from a lesser actor, but he holds the attention perfectly. Harrelson's role is more solid and conventional, but it contrasts well with Cohle and is no less compelling. I honestly believe that you could just show the interviews without the flashback and it would still be good watching.
The direction and script are equally good and a third component, even a third actor really, is the atmospheric Louisiana countryside, part industrial (a strong feature being the refineries and chemical works supporting oil industry along the Gulf coast) and still very rural and religious.
Very, very recommended.
Tuesday, 15 July 2014
Jack the Giant Slayer
A retelling of the old fairy tale, Jack (Nicholas Hoult) takes his horse to the City market to sell, exchanging it for some mysterious beans and embroiling himself with the Princess (Eleanor Tomlinson) and the King's scheming advisor (Stanley Tucci).
An amiable story, well told, with a good supporting cast including Ewen Bremner, Eddie Marsan, Ian McShane and Ewan McGregor. More fun than you would think and very recommended.
An amiable story, well told, with a good supporting cast including Ewen Bremner, Eddie Marsan, Ian McShane and Ewan McGregor. More fun than you would think and very recommended.
Sunday, 29 June 2014
BDD and JBehave
I've been in my new job for a few weeks now and encountered Behavior Driven Development in the code I'm looking at, using JBehave.
BDD is a way of structuring unit tests in such a way as to make them more human-readable. Typically, a conventional unit test looks something like this (this is for a small builder class I’ve created):
This is quite a small test, but it’s easy to see that someone non-technical would have difficulty following what was going on here. Plus it’s not very flexible: if you want to test boundary conditions, for example, you either have to do a lot of cut-and-pasting or some fancy footwork with the test libraries.
Compare this to the equivalent BDD statement (called stories):
This is supported in the test harness by methods bound to the statements in the story:
Not only is the story more readable, but you can parameterise the calls, setting up tables of inputs and expected outputs. Nice.
BDD is a way of structuring unit tests in such a way as to make them more human-readable. Typically, a conventional unit test looks something like this (this is for a small builder class I’ve created):
@Test public void testOneWhere() { //select with one criteria SQLBuilder instance = new SQLBuilder(); instance.select().table("A_TABLE"); String result = instance.where("A_COLUMN", "A_VALUE").build(); assertTrue("result is not proper SQL: " + result, result.equals("SELECT * FROM A_TABLE WHERE A_COLUMN = \"A_VALUE\"")); }
This is quite a small test, but it’s easy to see that someone non-technical would have difficulty following what was going on here. Plus it’s not very flexible: if you want to test boundary conditions, for example, you either have to do a lot of cut-and-pasting or some fancy footwork with the test libraries.
Compare this to the equivalent BDD statement (called stories):
Scenario: with a where clause Given a new SQLBuilder object When select is called And table is set to A_TABLE And where is set to A_COLUMN equals A_VALUE And build is called Then the result is SELECT * FROM TABLE WHERE A_COLUMN = "A_VALUE"
This is supported in the test harness by methods bound to the statements in the story:
@When("select is called") public void selectIsCalled() { sqlBuilder.select(); } @When("table is set to $table") public void tableSetToTable(String table){ sqlBuilder.table(table); } //etc.
Not only is the story more readable, but you can parameterise the calls, setting up tables of inputs and expected outputs. Nice.
Tuesday, 27 May 2014
Penny Dreadful
Imagine all the Gothic horror stories of the 19th Century, real and fictional. Throw them all together in Victorian London and you'd end up with something like this:
Seems a bit over the top for me, but the acting seems up to scratch.
Seems a bit over the top for me, but the acting seems up to scratch.
Monday, 19 May 2014
Goodbye to All That
Today was my last exam at Bromley for the Foundation Degree Course. It was Computer Systems, i.e. assembler and digital circuits using something called VHDL. My least favourite subjects on the course.
I've done very well at the development side of the course, pulling out all the stops and getting 91% in the object-oriented software development assignment, for which I won (jointly) first prize:
Rather expensive, too.
It's been an adventurous two years, something I never thought I'd be able to do, but I did it and that's something.
I've done very well at the development side of the course, pulling out all the stops and getting 91% in the object-oriented software development assignment, for which I won (jointly) first prize:
Rather expensive, too.
It's been an adventurous two years, something I never thought I'd be able to do, but I did it and that's something.
Wednesday, 14 May 2014
Introduction to Neo4j
Neo Technologies run little evening seminars to introduce their graph database technology and I took the liberty of attending one yesterday evening. You get a free book!
They're based around the back of the Tate Modern, in an area which seems like an extension of Shoreditch with loads of start-ups and overpriced coffee.
It was a very interesting presentation, given by Rik Van Bruggen (Belgian), giving the background to the database and a really good demo using belgian beers as a dataset. Neo4j also has a community version that you can download as well as a free on-line course (with registration).
Rick also demonstrated a web site that visualises recommendations in Amazon.com, which is quite groovy.
They're based around the back of the Tate Modern, in an area which seems like an extension of Shoreditch with loads of start-ups and overpriced coffee.
It was a very interesting presentation, given by Rik Van Bruggen (Belgian), giving the background to the database and a really good demo using belgian beers as a dataset. Neo4j also has a community version that you can download as well as a free on-line course (with registration).
Rick also demonstrated a web site that visualises recommendations in Amazon.com, which is quite groovy.
Sunday, 11 May 2014
Premiership Blues
Y'know a while ago, I mentioned that it looked like Chelsea had the Premiership sewn up. Then Liverpool came into the running and it looked like they were going to win. Funny how things turn out...
Inch-by-inch, City took over the top slot, first from Arsenal, and then from Liverpool (Blue beating Red twice).
Even better is that not only have the people across town won nothing, they're not even in Europe, having been pipped by Tottenham. Sad, really. And funny. They'll be back, though. They're annoying like that.
It does feel weird, City winning things. Nice to have to get used to it, though.
Inch-by-inch, City took over the top slot, first from Arsenal, and then from Liverpool (Blue beating Red twice).
Even better is that not only have the people across town won nothing, they're not even in Europe, having been pipped by Tottenham. Sad, really. And funny. They'll be back, though. They're annoying like that.
It does feel weird, City winning things. Nice to have to get used to it, though.
Wednesday, 7 May 2014
UXB on the Wild Shore
Before I start my exams on Friday, in a kind of pilgrimage of sorts, I went for a walk on Shoeburyness sea front only to be faced by a long fence:
(Taken using the steam-driven mobile and thus the poor quality). There were signs on the fence explaining it's purpose:
Locals know that Shoeburyness was the army ordnance testing range for some years and still has a military/M.o.D. presence. Then again, the Luftwaffe used the river to guide them into London and could have dropped something on the way back; or it could be something related to the ammunition ship, the Richard Montgomery, sunk off the Isle of Sheppey, although that's mostly opposite Thorpe Bay, so that's alright, then.
(Taken using the steam-driven mobile and thus the poor quality). There were signs on the fence explaining it's purpose:
Locals know that Shoeburyness was the army ordnance testing range for some years and still has a military/M.o.D. presence. Then again, the Luftwaffe used the river to guide them into London and could have dropped something on the way back; or it could be something related to the ammunition ship, the Richard Montgomery, sunk off the Isle of Sheppey, although that's mostly opposite Thorpe Bay, so that's alright, then.
Saturday, 3 May 2014
Sid Meier's Ace Patrol
I'm always on the lookout for cheap games and I thought I'd check this one out.
I've managed to survive the missions so far:
It's £4.99 on Steam and, like all Sid Meier games, it has a certain charm and certainly fun. The game plays a little like Wings of Glory (what used to be Wings of War), a card-based miniatures game:
I've managed to survive the missions so far:
It's £4.99 on Steam and, like all Sid Meier games, it has a certain charm and certainly fun. The game plays a little like Wings of Glory (what used to be Wings of War), a card-based miniatures game:
Friday, 2 May 2014
Lego Simpsons
Now I like Lego and I like the Simpsons: yes, it's lost it's edge over the years, and I got into (and out of) Family Guy, but it's still pretty good. However, I'm not so sure about the latest Lego minifig series:
Apparently it's to go with one of the latest episodes:
Apparently it's to go with one of the latest episodes:
I must not complain about the new Lego minifigs. I must not complain about the new Lego minifigs.
I must not complain about the new Lego minifigs. I must not complain about the new Lego minifigs.
I must not complain about the new Lego minifigs. I must not complain about the new Lego minifigs.
I must not complain about the new Lego minifigs. I must not complain about the new Lego minifigs.
I must not complain about the new
I must not complain about the new Lego minifigs. I must not complain about the new Lego minifigs.
I must not complain about the new Lego minifigs. I must not complain about the new Lego minifigs.
I must not complain about the new Lego minifigs. I must not complain about the new Lego minifigs.
I must not complain about the new
Thursday, 1 May 2014
Wednesday - The Graphs of Gaming and Recruitment
Yesterday evening, I went to a presentation on Graph Databases (specifically Neo4j, who were the organisers), hosted by Skills Matter.
First up was Nigel Small who talked about Zerograph, a new container/server for Neo4j.
Nigel gave a quick overview of Zerograph, highlighting it's ability to host more than one database and the use of ZeroMQ (thus the name) to increase reliability and robustness. ZeroMQ is a message queue, which is a piece of software designed to buffer and schedule messages between two systems in a more controlled way than a direct connection. It also, in ZeroMQ's case, allows for temporary disconnections, saving the messages to be processed when the connection is resumed. How this works in practise is another matter.
One of things emphasised throughout the talks was the speed with which Neo4j processes queries and returns results. Graph databases are designed to cope with information which is highly relational in nature, so something that in standard SQL would take seconds or even minutes with multiple joins, takes a fraction of that in a graph database.
Next up was Matt Wright to talk about the work at his company Stitched regarding the use of Neo4j in social networks for recruiting.
A quite amusing presentation, Matt illustrated the problems with existing social networks, such as Facebook and LinkedIn, and how "private" networks could be used to give more authentic results.
The last speaker was Yan Cui, from GamesSys, to talk about his experiences using Neo4j to model his company's Freemium online game "Here Be Monsters".
The game is resource based and can be incredibly complex and interrelated, so any small change in the underlying data can have considerable consequences. They've tried to make changes by rule-of-thumb, but this proved too unwieldy, slow and error-prone, so they've been modelling it with Neo4j and had much better results.
One of the things mentioned during the presentations was Cypher. Being interested in cryptography, I was a little baffled, but this turns out to be the Neo4j equivalent of SQL:
Looks similar enough, although I can't see why they didn't call it Graph Query Language (GQL), which would be much more obvious.
First up was Nigel Small who talked about Zerograph, a new container/server for Neo4j.
Nigel gave a quick overview of Zerograph, highlighting it's ability to host more than one database and the use of ZeroMQ (thus the name) to increase reliability and robustness. ZeroMQ is a message queue, which is a piece of software designed to buffer and schedule messages between two systems in a more controlled way than a direct connection. It also, in ZeroMQ's case, allows for temporary disconnections, saving the messages to be processed when the connection is resumed. How this works in practise is another matter.
One of things emphasised throughout the talks was the speed with which Neo4j processes queries and returns results. Graph databases are designed to cope with information which is highly relational in nature, so something that in standard SQL would take seconds or even minutes with multiple joins, takes a fraction of that in a graph database.
Next up was Matt Wright to talk about the work at his company Stitched regarding the use of Neo4j in social networks for recruiting.
A quite amusing presentation, Matt illustrated the problems with existing social networks, such as Facebook and LinkedIn, and how "private" networks could be used to give more authentic results.
The last speaker was Yan Cui, from GamesSys, to talk about his experiences using Neo4j to model his company's Freemium online game "Here Be Monsters".
The game is resource based and can be incredibly complex and interrelated, so any small change in the underlying data can have considerable consequences. They've tried to make changes by rule-of-thumb, but this proved too unwieldy, slow and error-prone, so they've been modelling it with Neo4j and had much better results.
One of the things mentioned during the presentations was Cypher. Being interested in cryptography, I was a little baffled, but this turns out to be the Neo4j equivalent of SQL:
MATCH (n:Person)-[:KNOWS]->(m:Person) WHERE n.name="Alice"
Looks similar enough, although I can't see why they didn't call it Graph Query Language (GQL), which would be much more obvious.
Saturday, 26 April 2014
Saturday - The Future of Healthy Longevity
Today, I went to a presentation on longevity, quite a popular subject amongst the London Futurists, second only to the Singularity. It was done in three parts, the first by Phil Micans:
Phil discussed the issue that ran through all the presentations: that absolute longevity (how long you live) is only as important as how healthy you are, otherwise the suffering, and it's associated cost to society, make the extra years pointless. He mentioned various new technologies, especially peptides, which have produced amazing results, including growing back one chap's finger tip:
Next on was Avi Roy, who discussed the possible areas of research and narrowed it down to nine different areas, each area affecting different diseases to a greater or lesser extent:
The effect being that if you address one factor, affecting one type of illness, another illness replaces it. All the nine factors have to be tackled together.
The third speaker was Tuvi Orbach, who discussed the effect of lifestyle on longevity.
He's a bit of an advert for his subject, being 65. Healthy living!
Phil discussed the issue that ran through all the presentations: that absolute longevity (how long you live) is only as important as how healthy you are, otherwise the suffering, and it's associated cost to society, make the extra years pointless. He mentioned various new technologies, especially peptides, which have produced amazing results, including growing back one chap's finger tip:
Next on was Avi Roy, who discussed the possible areas of research and narrowed it down to nine different areas, each area affecting different diseases to a greater or lesser extent:
The effect being that if you address one factor, affecting one type of illness, another illness replaces it. All the nine factors have to be tackled together.
The third speaker was Tuvi Orbach, who discussed the effect of lifestyle on longevity.
He's a bit of an advert for his subject, being 65. Healthy living!
Wednesday, 16 April 2014
Dependency Injection with Google Guice
One of the problems that we get in software development, specifically in the design of software classes, is that of the connection between classes. If one class uses another directly, even though it works, this can cause problems later on and is known as "close coupling". Here is a mundane example:
OK, this is really mundane, but can see that MessageUser cannot use any other way of sending messages. If you want to use another means, say email, you'd have to either change what MessageSender does or change MessageUser to use a different class, call it EMailSender. However, we can now use an interface instead of a class:
You still have to change MessageUser, but to use an interface given to, or "injected" into, the MessageUser object via the constructor:
This works if we then, in the main class, create the object that implements the MessageSender and pass it to, or inject it into, the MessageUser object:
Now if we want to have MessageUser send emails we create a class which also implements the MessageSend interface:
All that then has to be done is create an object of this class in the main class and then pass it to MessageUser, as before:
This technique, known as Dependency Injection, is quite an important design pattern and is mandatory in certain frameworks, such as Spring.
So far, so good, and it's difficult to see how this can be really improved upon. However, Guice (pronounced with a J rather than a G) does for dependency injection what Mockito does for unit testing. To introduce Guice into the above example, we have to create another class, an extension of Guice's AbstractModule class:
You can sort-of see what's going on. The module is responsible for creating the class that implements the interface, so whenever the interface is used, the object is bound to it. The magic happens in the Injector, used in the main class:
Notice that the module hasn't been told about MessageUser, so the Injector is figuring out it's dependencies from the constructor of the class, and this also has to change using the @Inject annotation:
Now all this doesn't seem like a big deal, if anything we've added lines and classes, but if you've got a lot of classes with umpteen dependencies, Guice can save you a lot of work.
//a really dumb message sending class public class MessageSender { public void sendMessage(String message) { System.out.println(message); } } //another dumb class that uses the message sender public class MessageUser { //a reference to the sender object private MessageSender messageSender; //the message sender object is created in the constructor public MessageUser() { this.messageSender = new MessageSender(); } //send the message via the sender public void sendMessage(String message) { messageSender.sendMessage(message); } } //the main class that uses the message classes public class MessageMain { public static void main(String[] args) { MessageUser messageUser = new MessageUser(); messageUser.sendMessage("This is a test"); } }
OK, this is really mundane, but can see that MessageUser cannot use any other way of sending messages. If you want to use another means, say email, you'd have to either change what MessageSender does or change MessageUser to use a different class, call it EMailSender. However, we can now use an interface instead of a class:
public interface MessageSender { public void sendMessage(String message); } //an implementation of the interface public class SystemMessageSender implements MessageSender { public void sendMessage(String message) { System.out.println(message); } }
You still have to change MessageUser, but to use an interface given to, or "injected" into, the MessageUser object via the constructor:
public class MessageUser { //a reference to the interface private MessageSender messageSender; //the interface is sent to the object using the constructor public MessageUser(MessageSender messageSender) { this.messageSender = messageSender; } public void sendMessage(String message) { messageSender.sendMessage(message); } }
This works if we then, in the main class, create the object that implements the MessageSender and pass it to, or inject it into, the MessageUser object:
public class MessageMain { public static void main(String[] args) { SystemMessageSender messageSender = new SystemMessageSender(); MessageUser messageUser = new MessageUser(messageSender); messageUser.sendMessage("This is a test"); } }
Now if we want to have MessageUser send emails we create a class which also implements the MessageSend interface:
//an implementation of the interface public class EMailMessageSender implements MessageSender { public void sendMessage(String message) { EMail.textMessage(message); } }
All that then has to be done is create an object of this class in the main class and then pass it to MessageUser, as before:
EMailMessageSender messageSender = new EMailMessageSender(); MessageUser messageUser = new MessageUser(messageSender); messageUser.sendMessage("This is a test");
This technique, known as Dependency Injection, is quite an important design pattern and is mandatory in certain frameworks, such as Spring.
Introducing Google Guice
So far, so good, and it's difficult to see how this can be really improved upon. However, Guice (pronounced with a J rather than a G) does for dependency injection what Mockito does for unit testing. To introduce Guice into the above example, we have to create another class, an extension of Guice's AbstractModule class:
public class MessageModule extends AbstractModule { protected void configure() { bind(MessageSender.class).to(SystemMessageSender.class); } }
You can sort-of see what's going on. The module is responsible for creating the class that implements the interface, so whenever the interface is used, the object is bound to it. The magic happens in the Injector, used in the main class:
Injector injector = Guice.createInjector(new MessageModule()); MessageUser messageUser = injector.getInstance(MessageUser.class); messageUser.sendMessage("This is a test");
Notice that the module hasn't been told about MessageUser, so the Injector is figuring out it's dependencies from the constructor of the class, and this also has to change using the @Inject annotation:
@Inject public MessageUser(MessageSender messageSender) { this.messageSender = messageSender; }
Now all this doesn't seem like a big deal, if anything we've added lines and classes, but if you've got a lot of classes with umpteen dependencies, Guice can save you a lot of work.
Tuesday, 15 April 2014
Captain America: The Winter Soldier
Being (relatively) cheap Tuesday at Empire Cinemas on th' BasVegas Strip, I took advantage and went to see the latest in the Marvel Avengers franchise. Now an agent of S.H.I.E.L.D., Steve Rogers, a.k.a. Captain America, is confronted with a conspiracy when Nick Fury is attacked.
There's lots of bangs and crashes and a reasonably decent plot, but is a Superhero movie at heart despite higher ambitions. All the team turn up, so it ends up being an Avengers movie without the Avengers, but the acting is ok, if a little pedestrian (it seems a long time ago since Robert Redford was in All The President's Men) and there's a fair number of cameo's, but it's Samuel Jackson, as Nick Fury, and Chris Evans, as th' Cap', that drive the movie.
There's lots of bangs and crashes and a reasonably decent plot, but is a Superhero movie at heart despite higher ambitions. All the team turn up, so it ends up being an Avengers movie without the Avengers, but the acting is ok, if a little pedestrian (it seems a long time ago since Robert Redford was in All The President's Men) and there's a fair number of cameo's, but it's Samuel Jackson, as Nick Fury, and Chris Evans, as th' Cap', that drive the movie.
Saturday, 12 April 2014
Salute 2014
For a change of pace, I went along to Salute 2014, the South London Warlords exhibition at Excel in the London Docklands.
There was a good turn out, with several different styles; historic, fantasy, science fiction and even horror (i.e. zombies), as well as the usual stalls. This was a large scale miniatures battle of Trebbia (Second Punic War: Hanibal vs. Roman Republic):
There was also a very large simulation of Sword Beach, one of the British D-Day landings:
as well as a Space 1889 attack on a Martian city by British Forces:
I got tempted by the stalls, eventually, and bought some model bases from Micro Arts Studio:
Nice!
There was a good turn out, with several different styles; historic, fantasy, science fiction and even horror (i.e. zombies), as well as the usual stalls. This was a large scale miniatures battle of Trebbia (Second Punic War: Hanibal vs. Roman Republic):
There was also a very large simulation of Sword Beach, one of the British D-Day landings:
as well as a Space 1889 attack on a Martian city by British Forces:
I got tempted by the stalls, eventually, and bought some model bases from Micro Arts Studio:
Nice!
Wednesday, 9 April 2014
Silicon Valley/Beta's - How Not To Run a Start-up
On Boing-Boing, there's a review of a series starting in the 'States called Silicon Valley, a comedy about a programmer who develops a new compression algorithm and, instead of selling out for gazzilions, takes some seed money and tries to run his own start-up. All very Microserf's:
However, this is not the first time programmers have been on the small screen in a comedy. A few months ago, Amazon created Beta's:
I'd normally just cringe and move on (they're not as good as The IT Crowd by the looks of things)
but the other day I expanded my Douglas Coupland collection with jPod and The Gum Thief. jPod was also made into a TV series, sadly unavailable.
However, this is not the first time programmers have been on the small screen in a comedy. A few months ago, Amazon created Beta's:
I'd normally just cringe and move on (they're not as good as The IT Crowd by the looks of things)
but the other day I expanded my Douglas Coupland collection with jPod and The Gum Thief. jPod was also made into a TV series, sadly unavailable.
Sunday, 6 April 2014
Mockito Spies
That is the collective noun, not the verb, although I suppose Mockito is spying...
Spies are used to make existing classes into Mockito classes. Say your class under test hooks into a Java listener, so you want some kind of dummy listener for it to hook into. You can't do this with Mockito (at least I can't find a way), but you can make your own:
Spies are used to make existing classes into Mockito classes. Say your class under test hooks into a Java listener, so you want some kind of dummy listener for it to hook into. You can't do this with Mockito (at least I can't find a way), but you can make your own:
//listener interface public interface SomethingListener { //change that sends the event public void somethingChanged(EventObject e); } //our little dummy listener provider public class DummyListenerProvider { private SwitchListener listener; //this is used by the class under test public void addSwitchListener(SwitchListener listener) { this.listener = listener; } //send event, saying the class is the source public void triggerEvent() { this.listener.somethingChanged(new EventObject(this)); } //used by the event consumer when the event occurs public void switchMeOn(boolean isTrue) { } }Cool, but you still want all the nice little trinkets that come with the Mockito objects. This is where spies come in. You just wrapper the class using spy instead of mock:
DummyListenerProvider spyListenerProvider = spy(new DummyListenerProvider()); ClassUnderTest underTest = new ClassUnderTest(spyListenerProvider); spyListenerProvider.triggerEvent(); verify(spyListenerProvider).switchMeOn(true);
Saturday, 5 April 2014
Mockito - An Elegant Stub for a More Civilised Age
In software development, we make use of something called "stubs". These are bits of code that don't do anything at the moment, but allow us to continue coding elsewhere as if they do, replacing them later. They are also used in testing to substitute for more complex objects, and this is where "mocking" (creating "mock" objects) has been developed in object-oriented programming and test-driven development.
As an extension to the college work I've been doing, I've been looking into using mock libraries for unit testing and I've come across Mockito:
The mock objects it creates are, well, amazing to say the least. Say we've got an interface that, in turn, allows us to create a read I/O stream and a write I/O stream, for networking. The interface would look something like this:
Now I can actually mock this interface with Mockito in the unit test:
Now, unfortunately, the mock doesn't really do anything other than just record what happens to it. Say SocketThread calls socket.close internally when it runs:
As an extension to the college work I've been doing, I've been looking into using mock libraries for unit testing and I've come across Mockito:
The mock objects it creates are, well, amazing to say the least. Say we've got an interface that, in turn, allows us to create a read I/O stream and a write I/O stream, for networking. The interface would look something like this:
//simple interface wrapper around a network socket public interface MySocket { //creates a read I/O stream public BufferedReader getBufferedReader() throws IOException; //creates a write I/O stream public PrintWriter getPrintWriter() throws IOException; //indicates that a connection has been successfully made public boolean isConnected(); //closes the connection public void close() throws IOException; }
Now I can actually mock this interface with Mockito in the unit test:
import static org.mockito.Mockito.*; ... MySocket socket = mock(MySocket.class);You can now use this mock socket interface in whatever need the interface, so:
SocketThread socketThread = new SocketThread(socket);
Now, unfortunately, the mock doesn't really do anything other than just record what happens to it. Say SocketThread calls socket.close internally when it runs:
//this is in SocketThread.run socket.close(); ... //if this isn't true, you'll get an exception verify(socket).close();Useful, but it becomes a bit more powerful when we add mocks for the input and output streams:
PrintWriter printWriter = mock(PrintWriter.class); BufferedReader bufferedReader = mock(BufferedReader.class); when(socket.getBufferedReader()).thenReturn(bufferedReader); when(socket.getPrintWriter()).thenReturn(printWriter);You can control exactly what the mock does and when it does it. Very useful for unit testing (and I haven't even begun to use all it's capabilities).
Thursday, 3 April 2014
Flight
Through my LoveFilm/Amazon subscription, this is a film starring Denzel Washington about a man facing up to his own frailties and responsibilities.
After saving most of the crew and passengers of his stricken airliner in a miraculous landing, William "Whip" Whitaker has to deal with problems of his own.
With an excellent story, it's a really good film about a man struggling with his demons. Denzel is a strong central lead, as to be expected, and has an excellent supporting cast, including Don Cheadle, Bruce Greenwood and John Goodman, but Kelly Reilly is good as his girlfriend trying to get him to recognise that he has a problem.
After saving most of the crew and passengers of his stricken airliner in a miraculous landing, William "Whip" Whitaker has to deal with problems of his own.
With an excellent story, it's a really good film about a man struggling with his demons. Denzel is a strong central lead, as to be expected, and has an excellent supporting cast, including Don Cheadle, Bruce Greenwood and John Goodman, but Kelly Reilly is good as his girlfriend trying to get him to recognise that he has a problem.

Subscribe to:
Posts (Atom)