DaedTech

Stories about Software

By

JUnit for C# Developers 8 – Obeying Demeter and Going Beyond the Tests

Last time in this series, I pulled an “Empire Strikes Back” and ended on a bit of a down note. This time around, I’d like to explore how I’ve alleviated my Law of Demeter problems, and about how fixing a code smell in my tests pushed me into a better design.

Up until now, I’ve been blogging as I go, but this one is all in the past tense — the work is done as I type this. I set out tonight with only one goal, get rid of my LOD violations, and this is where it took me.

Rethinking my Class

Recall that last time, I was passing in a database object, querying that for a collection, querying that for a cursor, and then querying the cursor for my actual database objects that I parsed and returned from the service. After a bit of trial and error and research, I decided that my service class needed to encapsulate the collection since, as best as I can tell from whatever Eclipse’s version of Intellisense is called, cursors are forward only and then you need to get another one. So, if I don’t pass in the collection at least, my service method will only work once. Fine – not thrilled about the collection.cursor.objects thing, but it’s at least pulling one LOD violation out.

I now have a handful of tests that look like this:

@Test
public void returns_room_model_with_roomName_from_database_room_key() {
	
	String myRoomName = "Rumpus Room.  Yeah, that's right.  I said Rumpus Room.";
	
	DBObject myMockDatabaseObject = mock(DBObject.class);
	Mockito.when(myMockDatabaseObject.get(RoomServiceMongoImpl.ROOM_NAME_KEY)).thenReturn(myRoomName);
	
	DBCursor myMockCursor = mock(DBCursor.class);
	Mockito.when(myMockCursor.next()).thenReturn(myMockDatabaseObject).thenReturn(myMockDatabaseObject).thenReturn(null);
	Mockito.when(myMockCursor.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false);
			
	DBCollection myMockCollection = PowerMockito.mock(DBCollection.class);
	Mockito.when(myMockCollection.find()).thenReturn(myMockCursor);
	
	RoomServiceMongoImpl myService = BuildTarget(myMockCollection);
	
	assertEquals(myRoomName, myService.getAllRooms().toArray(new Room[2])[0].getRoomName());
}

and my class became:

public class RoomServiceMongoImpl implements RoomService {

	public static final String ROOM_CODE_KEY = "room_code";

	public static final String ROOM_NAME_KEY = "room";
	
	private DBCollection _collection;
	
	public RoomServiceMongoImpl(DBCollection collection) {
		_collection = collection;
	}

	@Override
	public Collection<Room> getAllRooms() {
		Collection<Room> myRooms = new ArrayList<Room>();
		
		DBCursor myCursor = _collection.find();
		while(myCursor != null && myCursor.hasNext()) {
			RoomModel myModel = buildRoomModel(myCursor.next());
			if(myModel != null)
				myRooms.add(myModel);
		}
		
		return myRooms;
	}
	
	private RoomModel buildRoomModel(DBObject roomObject) {
		Object myRoomName = roomObject.get(ROOM_NAME_KEY);
		char myRoomCode = getRoomCode(roomObject.get(ROOM_CODE_KEY));
		
		if(myRoomName != null) {
			return new RoomModel(myRoomName.toString(), null, myRoomCode);
		}
		return null;
	}

	private char getRoomCode(Object myRoomCode) {
		return myRoomCode != null && myRoomCode.toString() != null && myRoomCode.toString().length() > 0 ?
				myRoomCode.toString().charAt(0) : 0;
	}
}

A lot cleaner and more manageable following some good TDD if I do say so myself (though I may be whiffing on some finer points of the language as I’m still rusty from 2 years of mostly uninterrupted C#). I’m still not thrilled about the heavy test setup overhead, but I’ve made incremental progress.

Now, where things got interesting is in wiring this up through Spring and MongoDB. The class works in test, but I need now to figure out how to use my spring-servlet.xml to get an instance of the collection injected into my class’s constructor. I wanted to do this (1) without defining any additional code and (2) without resotring to static implementations or singletons. For (1) I’d rather leave the DB setup stuff in XML as much as possible and for (2) I try to avoid static at all costs unless there’s some compelling argument that doesn’t lean prominently on a premise of “it’s more convenient”. Static is about as flexible as a diamond.

So, here is what I did:

<!-- This is the "Mongo" object where you specify connection credentials -->
    <bean id ="mongo" class="com.mongodb.Mongo">
    	<constructor-arg index="0" type="java.lang.String" value="192.168.2.191"/>
    </bean>
    
    <!--  This is the database returned from the mongo object (the daedalus) database -->
    <bean id="mongoDatabase" factory-bean="mongo" factory-method="getDB">
    	<constructor-arg index="0" value="daedalus"/>
    </bean>
    
    <!-- This is the "house" collection, which is a collection of rooms  -->
    <bean id="mongoHouseCollection" factory-bean="mongoDatabase" factory-method="getCollection">
    	<constructor-arg index="0" value="house"/>
    </bean>

I discovered that I can use factory-bean and factory-method attributes to invoke instance methods on beans that I’d created, turning their return values into other beans. I also learned that “constructor-arg” is rather unfortunately named in that it actually just translates to “arguments to the method in question”. So, in the case of the mongoDatabase bean, I’m getting it from my mongo object’s getDB() method with a string parameter of “daeadlus”. On the whole, the beans above translate to new Mongo(“192.168.2.191″).getDB(“daedalus”).getCollection(“house”) being stored in the “mongoHouseCollection” bean, which I injected into my service. When I wired and fired it, it worked perfectly the first time.

So, this post has been a little thin on actual information about JUnit (really just the denouement to my last post), but there is a nugget in here for spring wireup, and, I think the most important lesson for me is that the design benefits to TDD go beyond just code. By taking my test smell seriously, I wound up with a design where I completely factored the database setup garbage out of my code, which is clearly a good thing. Now, I’ve been around the block enough times that this would have happened regardless, but it was interesting to note that making a testability/clean-code decision and sticking to my guns teased out a macroscopic design improvement.

By

JUnit for C# Developers 7 – Law of Demeter and Temporal Mocking

Last time in this series, I posted about a good reminder of a couple of principles of good object oriented design (respecting the Law of Demeter and avoiding static method invocations as much as possible). Today, I’m going to double back on this consciously a bit to explore some more possibilities in JUnit. Don’t worry – I will fix the design in subsequent posts.

Goals

Today, I’d like to accomplish the following:

  1. Have a mock change with each invocation
  2. Mock a low of demeter violation in as little code as possible

To the Code!

If you’ve followed my last few posts, you’ve noticed that I setup MongoDB. So, logically, the next step is connecting to it with my application, and the next step after that is mocking this connection so that I can unit test the logic (well, since I’m following TDD, technically the mocking comes first). Through trial and error in a throw-away piece of code, I discovered that I could access my database as so:

public class HouseServiceMongoImpl implements HouseService {

	private Mongo _mongoConnection;
	
	private DB _database;
	
	public HouseServiceMongoImpl() {
		try {
			_mongoConnection = new Mongo( "192.168.2.191" , 27017 );
			_database = _mongoConnection.getDB("daedalus");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MongoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public House getHouse() {
		DBCollection myCollection = _database.getCollection("house");
		DBCursor myCursor = myCollection.find();
				
		List<String> myStrings = new ArrayList<String>();
		
		while(myCursor.hasNext()) {
			myStrings.add(myCursor.next().get("room").toString());
		}
		return new HouseModel(myStrings);
	}
	
}

Notice here that I’ve inlined instantiation of my dependencies in a form bad for testability. I won’t repeat this mistake in the actual, TDD version. This was just for me to see what actually worked and provide some context for what I’m trying to do. In my real class, RoomServiceMongoImpl, I’m going to be returning a collection of room objects, rather than a house object. So, without further ado, on to the TDD. To get things started, I wrote the following test:

public class RoomServiceMongoImplTest {

	private static RoomServiceMongoImpl BuildTarget(DB database) {
		
		return new RoomServiceMongoImpl(database);
		
	}
		
	public static class getAllRooms {
		
		/*
		 * If the driver gives us back nothing for this collection, return an empty collection to clients
		 */
		@Test
		public void returns_empty_list_when_database_get_collection_returns_null_for_house() {
			
			DB myMockDatabase = mock(DB.class);
			Mockito.when(myMockDatabase.getCollection(Mockito.matches("house"))).thenReturn(null);
			RoomServiceMongoImpl myService = BuildTarget(myMockDatabase);
			
			assertEquals(0, myService.getAllRooms().size());
		}
	}
}

This allowed me to create the room service and inject into it the DB object, since as far as I can tell, I gain nothing by injecting the Mongo object. So, my first test is that we get back a null object in the form of an empty list when the MongoDB collection requested is empty. This makes sense, as it means we have no house (and thus no rooms).

When doing TDD, I’ve gotten in the habit of teasing out any control flow by varying up the return value of the method. So, the first test returns an empty collection. The next test will return count of one. The next will return a bunch. The one after that may go back to zero but in a different set of circumstances. This sort of progression allows me to make progress while covering all my bases. So, here, I’m going to do the setup necessary for a list with a single item to be returned.

But… as it turns out, this isn’t trivial. From my database, I’m getting a collection, which I’m asking for a database cursor, which I’m asking in a loop for an object called “next”, which I’m then asking for my actual room’s string value (its name). This has the Law-of-Demeter violating form db.getCollection().find().next().get(string). Ugh. That’s a lot of mocking, and creating mocks this way is the smell of LOD violations in your code. But, let’s suck it up for now and create the mocks:

@Test
public void returns_list_with_one_item_when_db_returns_matching_cursor() {

	DBObject myMockDatabaseObject = mock(DBObject.class);
	Mockito.when(myMockDatabaseObject.get(Mockito.anyString())).thenReturn("asdf");
	
	DBCursor myMockCursor = mock(DBCursor.class);
	Mockito.when(myMockCursor.next()).thenReturn(myMockDatabaseObject);
			
	DBCollection myMockCollection = PowerMockito.mock(DBCollection.class);
	Mockito.when(myMockCollection.find()).thenReturn(myMockCursor);
	
	DB myMockDatabase = mock(DB.class);
	Mockito.when(myMockDatabase.getCollection(Mockito.matches("house"))).thenReturn(myMockCollection);
	
	RoomServiceMongoImpl myService = BuildTarget(myMockDatabase);
	
	assertEquals(1, myService.getAllRooms().size());
}

This was particularly annoying to write since it cost me a good bit of frustration trying to figure out why I was getting cryptic error messages about the wrong return type. Turns out it was because the collection.find() method is final, requiring me to use PowerMockito (this stack overflow post ended my suffering and I voted the poster up both for the question and his self-answer as my way of saying thanks). But, I was done, and the following class made the test pass:

public class RoomServiceMongoImpl implements RoomService {

	/**
	 * This is the MongoDB database object we'll use for our queries
	 */
	private DB _database;
	
	/**
	 * Dependency injected constructor
	 * @param database
	 */
	public RoomServiceMongoImpl(DB database) {
		_database = database;
	}

	@Override
	public Collection<Room> getAllRooms() {
		Collection<Room> myRooms = new ArrayList<Room>();
		
		if(_database.getCollection("house") != null && _database.getCollection("house").find().next().get("bkag") != null) {
			myRooms.add(new RoomModel("blah", null, 'A'));
		}
		return myRooms;
	}
}

Hideous, with all of those LOD violations, but functional. So now, the next step is to factor the code toward something less obtuse with my TDD, and an excellent way to do this is the case of two strings in the database. But, in order to make that happen, the cursor mock’s next() method has to first return a DB object and then return null. It just so happens that this is goal number one, and it can be achieved as follows:

DBCursor myMockCursor = mock(DBCursor.class);
Mockito.when(myMockCursor.next()).thenReturn(myMockDatabaseObject).thenReturn(myMockDatabaseObject).thenReturn(null);
Mockito.when(myMockCursor.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false);

Note the chained returns calls. I took what I had in the previous test and turned it into this code, and then amended the expected size of the collection returned to be 2 using hasNext() and next(). I also had to go back and add similar code to the previous test for completeness sake. With this in place, the CUT getAllRooms() method became:

@Override
public Collection<Room> getAllRooms() {
	Collection<Room> myRooms = new ArrayList<Room>();
	DBCollection myCollection = _database.getCollection("house");
	if(myCollection != null) {
		DBCursor myCursor = myCollection.find();
		if(myCursor != null) {
			while(myCursor.hasNext()) {
				myRooms.add(new RoomModel(myCursor.next().get("asdf").toString(), null, 'A'));
			}
		}
	}
	return myRooms;
}

Man, that’s ugly. But, it works, and that’s what matters. We’re going to pretty this up and make it more robust later during the “refactor” cycles of red-green-refactor. So, on to goal number two, which is to compact the mock setup code somewhat. Granted, the pain of this setup indicates a design smell and there is a good argument that we should not deoderize these test smells. But, given that this is partially an endeavor for me to learn and blog about the mocking tools available with JUnit, I’m going to make an exception, with a promise to myself that I will pay off this loan of technical debt later by doing what I can to cut down on the database boilerplate I don’t need in this class. I came up with this:

@Test
public void returns_list_with_one_item_when_db_returns_matching_cursor() {

	DBObject myMockDatabaseObject = mock(DBObject.class);
	Mockito.when(myMockDatabaseObject.get(Mockito.anyString())).thenReturn("asdf");
			
	DB myMockDatabase = mock(DB.class);
	
	Mockito.when(myMockDatabase.getCollection(Mockito.matches("house"))).thenReturn(PowerMockito.mock(DBCollection.class));
	Mockito.when(myMockDatabase.getCollection(Mockito.matches("house")).find()).thenReturn(mock(DBCursor.class));
	Mockito.when(myMockDatabase.getCollection(Mockito.matches("house")).find().next()).thenReturn(myMockDatabaseObject).thenReturn(null);
	Mockito.when(myMockDatabase.getCollection(Mockito.matches("house")).find().hasNext()).thenReturn(true).thenReturn(false);
	
	RoomServiceMongoImpl myService = BuildTarget(myMockDatabase);
	
	assertEquals(1, myService.getAllRooms().size());
}

But, it throws a null reference exception on the first find() setup (second Mockito.when() line) and it doesn’t really save any code anyway, so I see no advantage to going this route. My instincts were against it anyway, and since it doesn’t work as fluidly as I hoped it might (I feel like I could probably get this fluent-style to work with enough persistence) and doesn’t save us code, forget it. Nothing ventured, nothing gained. I’ll have to be satisfied that this fluent-chaining appears possible, but might be a stone better left un-turned in favor of going back and cleaning up my code by eliminating LOD violations and generally seeking not to have them.

These posts are getting a little fewer and further between now as I’m less frequently blazing new trails in my work. I will probably check back in on this line of posts when I factor the design of this a bit, as kind of a MongoDB/JUnit fusion post.

By

JSTL Core ForEach Loop

Today, I was pleasantly surprised at how easy a time I had setting up some JSP pages to interact with my ongoing Java/Spring MVC home automation server. I seem to remember the setup for this being annoying in a past Java life, but my experience today was the opposite. So, here is a brief summary of what I did.

My plan is to install MongoDB to store the data that I’m going to use. I don’t know if this is the right choice, but it seems like a lightweight one in that I can always go “heavier” with a RDBMS later, if that seems warranted. There’s also a bit of a “let’s try it out” motivation for me in that I can add another tool to my toolbox in the process. But, that’s a task for another time (and probably another post). For now, I’m going to mimic having a persistence structure with the following java class:

public class HouseServiceBasicImpl implements HouseService {

	@Override
	public House getHouse() {
		// TODO replace with actual implementation
		List<String> myRoomList = Arrays.asList("Kitchen", "Dining Rooom", "Bedroom"); 
		return new HouseModel(myRoomList);
	}
}

The House interface currently contains only a collection of room names. Here is the controller that uses the service:

@RequestMapping("/rooms")
public class HouseRoomController {

	private HouseService _houseService;
	
	/**
	 * Dependency injected constructor
	 * @param service
	 */
	public HouseRoomController(HouseService service) {
		if(service == null)
			throw new IllegalArgumentException("service");
		
		_houseService = service;
	}

	@RequestMapping("/rooms")
	public ModelAndView rooms() {

		//@TODO get rid of the law of demeter violation here - this should just pass the house to the model and view
		ModelAndView myModelAndView = new ModelAndView();
		Collection<String> myRoomNames = _houseService.getHouse() == null ? new ArrayList<String>() : _houseService.getHouse().getRoomNames();
		myModelAndView.addObject("rooms", myRoomNames);
		
		return myModelAndView;
	}
}

All we do here is pull the list of rooms from the service, and add them as a model to a ModelAndView with key “rooms”. With that in place, I wrote the following jsp page:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<jsp:include page="header.jsp"/>

<table>
	<c:forEach var="roomName" items="${rooms}">
		<tr><td>
			<a class="button" href='<c:out value="${roomName}"/>.htm'><c:out value="${roomName}"/></a>
		</td></tr>
	</c:forEach>
</table>

From there, I wired up my spring-servlet.xml with all the proper beans and tried to build, only to get an error: “The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved.” After some mild poking around on google, I learned that I didn’t have “standard.jar” in my WEB-INF\lib folder, and I needed it there. I found the jar at this site, downloaded it, and stuck it in that folder, and I was able to build.

From there, I ran the app on the server, and got an exception, though this was easy to track down. I had omitted an equals somewhere. Once I corrected that, I saw my page with my three rooms, as expected. And, I was pretty pleased.

I don’t know if it’s that I’m a lot more experienced at programming in general, or if Spring/Java/Eclipse has gotten easier to setup and use, but everything is much easier for me this time around than I remember from some years back. I suspect it’s a little from column A and a little from column B. One of the things that the .NET world has always seemed to have on the Java world is that everything is easier to setup and hit the ground running with. It seems as though the Java community is making noticeable strides in this department.

By

Basic Spring MVC spring-servlet.xml Configuration

Tonight, I enjoyed a nice success. Specifically, I enjoyed the kind of success that I’ve found tends invariably to arise from using TDD — I wired some things together and discovered that everything just worked (well, at least my java code did – I did have a slight oops with javascript typos, but that’s to be expected in an environment where I get no feedback until runtime). And, what made this extra sweet is that I’m designing a server that turns lights on and off in my house. This means that at the eureka, breakthrough moment, you don’t find out from a running application or a successfully parsed file or anything as mundane as that. You’re treated to your house lighting up like a Christmas Tree to celebrate your success! (And then you’re thankful that the “off” also works because your sleeping girlfriend is probably not amused by this development.)

But, my purpose here is neither to gloat nor to stump for TDD. Instead, I wanted to give a nod to how easy it was for me to wire things up in Spring MVC 3, and what an improvement I perceive this to be from some years and versions back. Since I was doing TDD, I was basically isolating two classes that I have collaborating them and testing them individually. These classes are LightManipulationServiceHeyuImpl, which implements LightManipulationService and LightController:

public interface LightManipulationService {

	/**
	 * Turns the light in question on or off
	 * @param light - the light to toggle
	 * @param isOn - the setting (true for on, false for off)
	 * @return whether or not the operation was successful
	 */
	Boolean toggleLight(Light light, Boolean isOn);
	
	/**
	 * Change the brightness of a light
	 * @param light - the light to modify
	 * @param brightnessChange - the brightness change (positive for brighter, negative for dimmer)
	 * @return whether or not the operation succeeded
	 */
	Boolean changeBrightness(Light light, int brightnessChange);
}

public class LightManipulationServiceHeyuImpl implements LightManipulationService {

	public static final String OFF_COMMAND = "off ";

	public static final String ON_COMMAND = "on ";

	public static final String HEYU_COMMAND = "/usr/local/heyu-2.6.0/heyu ";
	
	private Runtime _runtime;
	
	/**
	 * Dependency injected constructor
	 * @param runtime - runtime to use for executing shell commands
	 */
	public LightManipulationServiceHeyuImpl(Runtime runtime) {
		if(runtime == null)
			throw new IllegalArgumentException("runtime");
		_runtime = runtime;
	}
	
	@Override
	public Boolean toggleLight(Light light, Boolean isOn) {
		try {
			String myCommand = isOn ? ON_COMMAND : OFF_COMMAND;
			return _runtime.exec(HEYU_COMMAND + myCommand + light.getLightCode()) != null;
		} catch (IOException e) {
			return false;
		}
	}

	@Override
	public Boolean changeBrightness(Light light, int brightnessChange) {
		// TODO Auto-generated method stub
		return null;
	}
}

RequestMapping("/light")
public class LightController {

	private LightManipulationService _lightService;
	
	public LightController(LightManipulationService lightManipulationService) {
		if(lightManipulationService == null) throw new IllegalArgumentException("lightManipulationService");
		_lightService = lightManipulationService;
	}

	@RequestMapping("/light")
	public ModelAndView light() {
		return new ModelAndView();
	}

	/**
	 * Toggles the light described by room and light names on or off (command)
	 * @param room - Name of the room we find this light in
	 * @param light - Name of the light itself
	 * @param command - Whether to turn the light on or off
	 */
	@RequestMapping(value="/{room}/{light}/{command}", method=RequestMethod.PUT)
	public void toggleLight(@PathVariable String room, @PathVariable String light, @PathVariable String command) {
		_lightService.toggleLight(new Light(room, light), command.toLowerCase().equals("on"));
	}
}

This was all tested and looking good for the time being, so I figured I’d take a break from implementation and, well, see if any of it actually worked. Up until this point, I hadn’t bothered with any wireup, so I figured this would be an adventure. But, it wasn’t. A little google-fu and everything worked. I figured it would be easy enough to declare beans to do setter injection (I remembered this from the Spring MVC 1 days), but I thought that I might get snagged a little with constructor injection. I thought I might get snagged a lot with the fact that I wanted to inject the result of the static method Runtime.getRuntime() into my service.

But, I had no trouble in either case.

    <bean id="shell" class="java.lang.Runtime" factory-method="getRuntime"/>
    
    <bean id="heyuService" class="com.daedtech.daedalus.services.LightManipulationServiceHeyuImpl">
    	<constructor-arg index="0" type="java.lang.Runtime" ref="shell"/>
    </bean>
    
    
    <bean id="lightController" class="com.daedtech.daedalus.controller.LightController">
    	<constructor-arg index="0" ref="heyuService"/>
    </bean>

The first thing I set up was my service, using the familiar bean id and class syntax. From here, I located the constructor injection tag, but decided to come back to it since I thought the static method was going to be ugly. I then created the lightController bean and this is when I found the syntax for the constructor injection tag: constructor-arg. I specified which 0-indexed constructor argument I was supplying and referred it to my service bean. Simple enough. I don’t know whether the index is necessary with only one parameter or not, but hey, it’s working. I’ll figure that out when I need to.

From there, the static thing was surprisingly and pleasantly easy. I don’t know whether Runtime.getRuntime() is actually considered a factory method or not, but by using it in this fashion, I was able to accomplish what I wanted. This is going to come in extremely handy for cases where I have to pull things out of some framework or library static state and I don’t want to take that inline dependency to impede flexibility/testability.

And, really, that was it. I fired this up with my unit tested classes and absolutely nothing happened. I peered at the JSP pages and the javascript in them, realized I had forgotten a comma, fired again, and was dazzled by the lightshow in my house. So kudos to Spring MVC. Easy and flexible is always nice.

By

JUnit for C# 3 – Mocks and Other Niceties

Edit: It occurs to me that the name here was kind of an oops. If you’re here to see how I use JUnit while developing in C#, you’re probably going to be disappointed. I meant to title this “JUnit for C# Developers 3″, but made a rather comical omission. My apologies.

As I go along with this series of posts, I’ve come to a decision. My plan is to get my new, open source home automation server working at the level of functionality my old, struts-based one currently works. I think I’m going to muddle through TDD and posting my adventures for as long as that takes, and then I’ll probably add it to github to see if anyone wants to pull, and move on to other posting topics (like my practical design patterns series that I’ve been a little slow on lately). But, for now, I’ll keep on with these.

Goals for Today

Since my last two posts were more of a whim, I decided to get organized a little now that I’m in the swing of it. So, my goals for today’s post are the following:

  1. Find out whether or not Java now supports optional parameters.
  2. Figure out how to assert that a method throws an exception
  3. Figure out how to run a single unit test only
  4. Get setup with a mocking framework.

I figure that’s a bite-sized chunk for an hour or two, so let’s get started.

Actual Work

So, first up is Java and default parameters. The answer there seems to be a resounding “no” (it’s acquired foreach and instanceof, so I figured it was worth a shot). I saw this stackoverflow post, and upvoted the question while I was at it, but the answer seemed to be no. Given that the post was somewhat outdated, I checked around in some other places as well with the same findings. Bummer. The reason I wanted to find this out for my TDD is that I’ve adopted a pattern of doing something like this for my tests:

        /*
	 * This is here for TDD to stop me from needing to change every test
	 * if I decide to inject a xtor param
	 */
	private static LightController buildTarget(LightManipulationService service = null) {
		LightManipulationService myService = service != null ? service : new MockLightManipulationService();
		return new LightController(myService);
	}

Basically, instead of directly instantiating the class under test (CUT), I delegate that responsibility to this builder method. That way, if I decide to add a constructor parameter to the CUT, I don’t have to bother with the tiresome chore of updating all of my tests. And, adding a constructor parameter is a rather frequent occurrence for me when doing TDD.

But, it turns out that I’ll have to settle for the noisiness of a method overload to accomplish this. Perhaps its the purist in me, but I think default parameters in C# (and other languages) are a much more elegant solution to this problem than method overloads. I hate boilerplate code — it’s just more places you have to maintain and more places mistakes could be made. So, first goal accomplished, if not in a satisfying way. More on the builder and supplying an interface to the controller later.

Next up, I want to add a constructor parameter to my controller, as you may have intuited. The purpose of this light controller is to allow a user to turn lights in my house on and off with a RESTful URL scheme. The actual mechanics of lights on/off is accomplished via a shell command that invokes a driver my server is running. However, it is wildly inappropriate for a presentation layer controller to know the details of how that works, so I’m abstracting out a conceptual service:

public interface LightManipulationService {

	/**
	 * Turns the light in question on or off
	 * @param light - the light to toggle
	 * @param isOn - the setting (true for on, false for off)
	 * @return whether or not the operation was successful
	 */
	Boolean toggleLight(Light light, Boolean isOn);
	
	/**
	 * Change the brightness of a light
	 * @param light - the light to modify
	 * @param brightnessChange - the brightness change (positive for brighter, negative for dimmer)
	 * @return whether or not the operation succeeded
	 */
	Boolean ChangeBrightness(Light light, int brightnessChange);
}

“Light” is a POJO that I made to encapsulate properties for the room containing the light and the name of the light. The controller will operate by parsing the URL For the room and light parameters and then passing a corresponding light object to the service, which will take care of the actual light operations in a nod to the single responsibility principle.

Now, I want to inject an implementation of this interface into my controller and, furthermore, I want to throw an exception if a client injects null. After all, the controller for lights can’t operate in any meaningful way if it doesn’t have a service that actually does things to the lights. And this is where goal number (2) comes in. It turns out that testing for a thrown exception is pretty straightforward:

@Test(expected=IllegalArgumentException.class)
	public void constructor_Throws_Exception_On_Null_Service_Argument() {
		new LightController((LightManipulationService)null);
	}

That’s all there is to it. As an aside, I’m pretty impressed with Eclipse’s ability to take action during my TDD. For instance, when I instantiated the controller this way, I got a red won’t-compile squiggly as one would expect. As an option for fixing, I was allowed to declare a new constructor, ala CodeRush in Visual Studio (truth be told, VS may offer this too, but I’ve been using CodeRush for so long I don’t remember).

Now, my next goal was figuring out how to run an individual test, mostly for my own edification. Back to stackoverflow where I upvoted another question and answer:

In the package explorer unfold the class. It should show you all methods. Right click on the one method you want to run, then select Run As -> JUnit from the context menu (just tested with Eclipse 3.4.1). Also selecting “Run” on a single entry in the JUnit-results view to re-run a test works in the same way.

Sure enough, that did it. I can run it by right clicking the method or by highlighting it and using Ctrl-Shift-X, T. This is good enough for now, though what I’d really like is the ability that CodeRush and Visual Studio both confer to run a test with a key shortcut with my cursor inside the test. Perhaps that’ll be a goal for next time.

Now, for the meat of this post, a mocking framework. After getting that last test to pass, I now have a problem in that my code won’t compile, since I have another test that needs to inject something into the controller to get it to pass. For a mocking framework, I decided on Mockito. I chose this framework based entirely on “what did James Shore use in Let’s Play TDD”. My philosophy, generally speaking, is “get it working, optimize later”, so picking any framework and using it is better than deliberating long and hard. And, if a guy like James is using it, it’s probably worthwhile.

Installation was easy. I downloaded the jar from the download site and created a directory in my eclipse folder called “externaljars” where I placed it. I have no idea if this is a good practice or not, but a tutorial I looked at suggested creating a C:\mockito directory and I really prefer not to create clutter in root or anywhere else. Until someone tells me why not to, I’ll just stick these things in a sub-directory of Eclipse that I include in my build path.

So, next, I included this directory in my build path. :) From there, I just added the mockito import and defined an overload that I mentioned while fulfilling goal (1), and I had this CUT:

@Controller
@RequestMapping("/light")
public class LightController {

	public LightController(LightManipulationService lightManipulationService) {
		if(lightManipulationService == null) throw new IllegalArgumentException("lightManipulationService");
	}

	@RequestMapping("/light")
	public ModelAndView light() {
		return new ModelAndView();
	}
}

And 4 passing tests:


package com.daedtech.daedalustest.controller;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.junit.Test;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.daedtech.daedalus.controller.LightController;
import com.daedtech.daedalus.services.LightManipulationService;

public class LightControllerTest {

	private static LightController buildTarget() {
		return buildTarget(null);
	}
	
	private static LightController buildTarget(LightManipulationService service) {
		LightManipulationService myService = service != null ? service : mock(LightManipulationService.class);
		return new LightController(myService);
	}
	
	@Test(expected=IllegalArgumentException.class)
	public void constructor_Throws_Exception_On_Null_Service_Argument() {
		new LightController((LightManipulationService)null);
	}
	
	@Test
	public void light_With_No_Parameters_Returns_Instance_Of_Model_And_View() {
		
		LightController myController = buildTarget();
		
		Assert.isInstanceOf(ModelAndView.class, myController.light());		
		
	}
	
	@Test
	public void light_Is_Decorated_With_RequestMapping_Annotation() throws NoSuchMethodException, SecurityException {
		
		Class<LightController> myClass = LightController.class;
		Method myMethod = myClass.getMethod("light");
		Annotation[] myAnnotations = myMethod.getDeclaredAnnotations();
		
		Assert.isTrue(myAnnotations[0] instanceof RequestMapping);
	}
	
	@Test
	public void light_RequestMapping_Has_Parameter_Light() throws NoSuchMethodException, SecurityException {
		
		Class<LightController> myClass = LightController.class;
		Method myMethod = myClass.getMethod("light");
		Annotation[] myAnnotations = myMethod.getDeclaredAnnotations();
		
		String myAnnotationParameter = ((RequestMapping)myAnnotations[0]).value()[0];
		
		assertEquals("/light", myAnnotationParameter);
	}
}

Now, we’re getting somewhere! This class is going to be functional pretty soon!

By

Setting Up AJAX and JQuery

AjaxSo, in response to feedback from my previous post about my   home automation server site, I’ve decided to incorporate AJAX and JQuery into my solution. This is partially because it’s The Right Thing ™ and partially because I’m a sucker for the proposition of learning a new technology. So, here are the steps I took toward going from my previous solution to a working one using AJAX, including downloads and other meta-tasks.

The first thing that I did was poke around until I found this tutorial, which is close enough to what I to do to serve as a blueprint. I found it very clear and helpful, but I realized that I had some legwork to do. I setup my java code as per the tutorial, but on the client side in JSP, I realized things wouldn’t work since I couldn’t very well source a jquery library that didn’t exist in the workspace. I poked around on my computer a bit and saw that I did have various jquery.js libraries, but they were part of Visual Studio, Android, and other concerns, so I figured I’d download one specifically for this task rather than try to reappropriate.

So, I went to jquery.com. I poked around a bit until I found the most recent “minified” version, since that’s what the example was using, and discovered it here. I was a little surprised to find that the ‘download’ would consist of copying it and pasting it into a local text file that I named myself, but I guess, what did I expect – this is a scripted language executed by browsers, not a C++ compiler or the .NET framework or something.

In Eclipse, I made a directory under my WebContent folder called “js”, and I put my new jquery-1.7.1.min.js file in it. Now, I had something to link to in my JSP page. Here is the actual link that I put in:

<script type="text/javascript" src="js/jquery/jquery-1.7.1.min.js"></script>

Just to make sure my incremental progress was good, I built and ran on localhost, and

My project now error’d on build and at runtime. For some reason, Eclipse seems not to like the minified version, so I switched to using the non minified. I still got a runtime error in Eclipse browser (though not in Chrome) and the javascript file had warnings in it instead of errors. This was rectified by following the high scoring (though strangely not accepted) answer on this stack overflow post.

However, it was at this point that I started to question how much of this I actually needed. I don’t particularly understand AJAX and JQuery, but I’m under the impression that JQuery is essentially a library that simplifies AJAX and perhaps some other things. The tutorial that I was looking at was describing how to send POST variables and get a response, and how this was easier with JQuery. But I actually don’t need the variables, nor do I need a response at this time. So, given the JQuery runtime errors that were continuing to annoy me, I deleted JQuery from the proiejct and resolved to work this out at a later date. From here, after a bit of poking around, I realized that using AJAX from within Javascript was, evidently, pretty simple. I just needed to instantiate an XMLHttpRequest object and call some methods on it. Here is what I changed my kitchen.jsp page to be:

<script type="text/javascript">
 function off() { 
	var http = new XMLHttpRequest();
 	http.open("POST", "kitchen/off.html", true);
 	http.send("");
 }
 function on() { 
	var http = new XMLHttpRequest();
 	http.open("POST", "kitchen/on.html", true);
 	http.send(""); 
}
</script>

<section id="content">
	<table>
		<tr><td><a href="javascript:void(0)" onClick="on()" class="button">Overhead On</a></td><td><a href="javascript:void(0)" class="button" onClick="off()">Overhead Off</a></td>
	</table>
	</section>
    
</body>
</html>

Pretty simple, though when you have no idea what you’re doing, it takes a while to figure out. :)

I instantiate a request, populate it and send it. Given my RESTful scheme, all the info the server needs is contained in the path of the request itself, so it isn’t necessary for me to parse the page or ask for a response. I added the javascript:void(0) calls so that the buttons would still behave like actual, live links. I think that later, when it is, I’ll probably bring JQuery back and revisit the tutorial that I found. Here is my updated controller class.

@Controller
@RequestMapping("/kitchen")
public class KitchenController {




	@RequestMapping("/kitchen")
    public ModelAndView kitchen() {
    	String message = "Welcome to Daedalus";
        return new ModelAndView("kitchen", "message", message);
    }
	
	@RequestMapping(value="/{command}", method = RequestMethod.POST)
	public @ResponseBody String kitchen(@PathVariable String command) {
		
		try {
			Runtime.getRuntime().exec("/usr/local/heyu-2.6.0/heyu " + command + " A2");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "";
	}
}

I’m fairly pleased with the asynchronous setup and the fact that I’m not playing weird games with redirect anymore. I have a unit test project setup, so I think I’m now going to get back to my preference of TDD, and factor the controller to handle more arbitrary requests, making use of an interfaced service for the lights and a data driven model for the different rooms and appliances. I’ve got my eye on MongoDB as a candidate for data storage (I’m not really doing anything relational), but if anyone has better ideas, please let me know.

By

Redirect Back with Spring 3.0 MVC

As I’m getting back into Java and particularly Spring MVC, it’s a bit of an adjustment period, as it always is when you’re dusting off old skills or trying something new. Things that should be easy are maddeningly beyond your reach. In light of that, I’m going to document a series of small milestones as I happen on them, in the hopes that someone else in my position or a complete newbie might find it useful.

So, today, I’m going to talk about processing a GET request without leaving the page. The reason I wanted to do this is that I have a page representing my house’s kitchen. The page has two buttons (really links styled as buttons through CSS) representing lights on and off. I’m providing a restful URL scheme to allow them to be turned on and off: kitchen/on and kitchen/off will turn the lights on and off, respectively. However, when this happens, I don’t have some kitchen/off.jsp page that I want handling this. I want them redirected right back to the kitchen page for further manipulation, if need be.

Here is how this was accomplished. Pay special attention to the kitchen() method taking the variable name and request as paramters:

@Controller
@RequestMapping("/kitchen")
public class KitchenController {

	@RequestMapping("/kitchen")
    public ModelAndView kitchen() {
    	String message = "Welcome to Daedalus";
        return new ModelAndView("kitchen", "message", message);
    }
	
	/*
	 * This takes kitchen and some request after it and satisfies the request
	 */
	@RequestMapping(value="/{name}", method = RequestMethod.GET)
	public String kitchen(@PathVariable String name, HttpServletRequest request) {
		try {
			Runtime.getRuntime().exec("/usr/local/heyu-2.6.0/heyu " + name + " A2");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "redirect:" + request.getHeader("Referer");
	}
}

So, the idea here is that I’m returning a redirect to the referrer. So, basic logic flow is that client sends an HTTP get request by clicking on the link. We process the request, take appropriate action, and then redirect back to where he started.

This certainly may not be the best way to accomplish what I’m doing, but it’s a way. And, my general operating philosophy is to get things working immediately, and then refactor and/or optimize from there. So, if you know of a better way to do it, by all means, comment. Otherwise, I’ll probably figure one out on my own sooner or later.

By

Setting Up Spring MVC 3.0

Why Spring MVC?

It’s been a while since I’ve done a lot with Java. I’ve been writing an Android app and see and interact with just enough Java not to forget what it looks like, but for the last couple of years, I’ve mainly worked in .NET with C#. Today, I started on actual development of my home automation server in earnest (will be added to github shortly). One of the main design goals of this home automation effort is to support affordable solutions and, toward that end, I am designing it to run on bare bones Linux machines, thus allowing old computers to be re-appropriated to run it.

This is the driving force in my choice of implementation tools. It needs to be runnable on Linux and Windows, and to have a small footprint. But, it also needs to support a true object oriented design paradigm and rich server side functionality. So, I will be dusting off my J2EE and using Spring MVC and Java for the server itself.

Setting up Spring MVC 3.0

I’ve been spoiled by developing principally in .NET over the last couple of years. In that world, any kind of project is usually a Visual Studio install and a plugin or NuGet package away. In the open source world of Spring and Java, it’s not quite as straightforward. My first step was, of course, a hello world app. I have plenty of Spring MVC/J2EE experience, but I was last developing with Spring when it was version 1.x, and we’re a few years removed and on 3.1, so I’m basically starting all over.

I already had Eclipse and Tomcat installed, and I set about finding an Eclipse plugin for creating a sample spring project or a tutorial on the same. I didn’t really find either. The most helpful thing I found, by far, was this blog post. If you take steps to satisfy the preconditions listed and follow the blog itself, you’ll be most of the way there.

I had to take two additional steps to get my new Spring “Hello World” project up and running. I had to get commons-logging.jar from the spring framework that I had downloaded and put it into my little app’s Web-INF\lib folder. I then had to do the same with jstl.jar from my Tomcat installation. Only after doing that was Hello World up and running.

Hopefully, this saves someone reading some time.

Acknowledgements | Contact | About | Social Media