DaedTech

Stories about Software

By

Basic Unit Testing with JUnit for C# Developers

As I’ve blogged previously, I’ve become increasingly dependent on TDD to the point where I’m basically addicted to the practice. I start to get nervous and twitchy if I’m writing code that isn’t driven by tests — it feels like putting a mop into a bucket of filthy water and then using it to ‘clean’. In other words, writing code without tests feels like pushing dirt around aimlessly while having no positive effect.

But, I digress. The purpose of this post today is to document my implementation of TDD in Java using JUnit, coming from two solid years of almost exclusive C# work. So, bear in mind that I may make some mistakes here or violate some best practices (and feel free to comment and correct me), but it’s my hope that I get the basics right and perhaps can help someone else going from C# to Java.

First Things First

I won’t go into a lot of detail here, but I’m using Eclipse and have set myself up for Spring development. I had created a small, working Spring web app, and I had a little code here, but wanted to test first with any new code. To do this, I followed my C#/Visual Studio instincts and went to create a separate project containing my tests. About 85% of people from a smattering of languages favored this approach in a poll by Phil Haack, and the approach earned an answer and a vote, if not top honors, on stackoverflow.

When you go this route in Eclipse, there is no JUnit project to create, so you just create a standard java project. I did this and populated it with a directory structure mirroring that of my actual application, putting the tests in the ‘same’ package as their class under test counterparts. And then, really all that was needed was to import the org.junit.Test library which, apparently, was already wherever it needed to be (I realize that this is not helpful if you don’t have it, but this really isn’t the emphasis of this post).

Onto the Tests

The first thing I did was to create a class called LightControllerTest, as I was interested in creating a LightController class. And, I need that class to have a method called light() that would return a ModelAndView. So, I created the following test:

package com.daedtech.daedalus.controller;

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

public class LightControllerTest {

	/*
	 * This should return an instance of model and view (apparently)
	 */
	@Test
	public void light_With_No_Parameters_Returns_Instance_Of_Model_And_View() {
		
		LightController myController = new LightController();
		
		Assert.isInstanceOf(ModelAndView.class, myController.light());		
		
	}
}

A few things to note here, fellow C# developers. One is that the equivalent of MSTest [TestMethod] is the java @Test annotation. This tells the test runner that this is a unit test. Another thing to note is that I’m using the spring framework’s assert, which may not be applicable if you’re not using Spring MVC. There is also JUnit’s assert available to you. I chose the Spring one because it had isInstanceOf(), which reminded me of MSTest’s “Assert.IsInstanceOfType()”.

So, with my test written and not compiling, I wrote the following code:

package com.daedtech.daedalus.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

	public ModelAndView light() {
		//return new ModelAndView();
		return null;
	}
}

Now, I was primed to have a red test instead of a non-compiling one, but I needed to run the test itself. In Eclipse, there are various ways of doing it, but the closest I could come to Ctrl-R, T was Alt-Shift-X, T. Good enough – that seems to scope them the way MSTest does as well, with only the one test running, even though I defined another in a different class. But, as with Visual Studio, there are a number of different ways to run the tests — from the little green “play” button dropdown, from the context menu right clicking on the project, from within the JUnit window that appears once you run the tests, etc. So, I ran the test, saw it fail, and deleted the return null line in favor of the one that would make it pass. A little contrived, I realize, but you’ll have to cut me a bit of slack as I iron out the early kinks. Later, I’ll write tests that fail before they pass — I promise.

I’ll have to play for a bit to get myself really familiar with the ins and outs, and I’ll probably follow with more posts like this. I’m also going to be muddling my way through other random issues like “is it appropriate (or even possible) to test that a method is annotated” and “is there anything like NCrunch for Java/Eclipse”? Stay tuned! 🙂

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:


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:



Overhead OnOverhead Off

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

Adding a Google Map to Android Application

I’m documenting here my first successful crack at adding a google map to an android application. Below are the steps I followed, with prerequisite steps of having the Android SDK and Eclipse installed, and being all set up for Android development (documented here).

  1. Created a new Android project
  2. Navigated to Help->Install New Software in Eclispe.
  3. Added a new source with URL http://dl.google.com/eclipse/plugin/3.7
  4. Selected all possible options (why not, right?) to have access to the google API in general.
  5. This install took about 5 minutes, all told, and I had to restart Eclipse
  6. In my new project, I navigated to project properties and went to Android, where I selected (the newly available) “Google APIs”
  7. From here, I got excited and ran my project, and was treated to a heaping helping of fail in the form of an error message saying that I needed API version 9 and my device was running API version 8 (Android 2.2.1). I fixed this by opening the manifest and changing the uses-sdk tag’s android:minSdkVersion to 8. Then when I ran, I had hello world on my phone. (Later, when all was working, I just deleted this line altogether, which eliminated an annoying build warning)
  8. With that in place, I added the node

    to my application node in the same manifest XML file.

  9. Then, as I discovered in an earlier post, I had to add
  10. From there, I followed the steps in this tutorial, starting at number 4.
  11. One thing to watch for in the tutorial is that you should add the lines about the map view after all boilerplate code already in onCreate or mapView will be set null and you’ll dereference it.

With all of this, if you ignore the bit about the API key, what you’ll wind up with is a map with no overlay on your phone. That is, it looks like everything is normal, including zoom icons, but the map hasn’t loaded yet. This was the state I found myself in when I decided that I’d take the last step and get the API key. This was not at all trivial.

I understand that if you’re familiar with the concept of signing software for distribution in app market, this probably makes sense. But, if this isn’t something you’ve been doing, it comes straight out of left field and, what’s more, there was no real place where how to do this was described in any detail. So, I’ll offer that here.

  1. Navigate to your JAVA_HOME bin folder (wherever your java and javac executables are)
  2. Run the command
    keytool -v -list {keystore}

    . The -v is important because this gives yo all the fingerprints (the default is SHA1, which won’t help you in the next step — you want MD5). The keystore is going to be debug.keystore, which is what your device uses for signing when you’re developing and not releasing. For me, this was located in C:\documents and settings\erik\.android on this win XP machine (YMMV with the directory)

  3. What you’ve done here is generated a fingerprint for the developer debug keystore that Eclipse automatically uses. This is fine until you want to deploy the app to an app store, at which time you’ll have to jump through a few more hoops.
  4. Take the key that this spits out and copy it (right click and select “mark” in cmd window), and paste it into the “my certificate’s MD5 fingerprint” text box here: http://code.google.com/android/maps-api-signup.html
  5. This will give you both your fingerprint, and an example layout XML to use in your Android map project
  6. Copy this into your project’s layout, following the guide for naming the attribute that contains the key. (That is, find your layout’s com.google.android.maps.MapView node and set its android:apiKey attribute to the same as the one on the page you’re looking at.
  7. Once you’ve got this, you can paste it into your map layout, run your app (phone or emulator) and get ready to start navigating to your heart’s content

After I went through all this, I found this clearly superior tutorial: http://mobiforge.com/developing/story/using-google-maps-android. This is really great for getting started, complete with code samples and starting as simple as possible.

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.