DaedTech

Stories about Software

By

IntelliJ IDEA: Saying Goodbye to Eclipse

I received a recommendation from Ted Young recently to try a switch to IntelliJ IDEA as an alternative to Eclipse IDE. I’ve been using Eclipse for years, but figured I’d give this tool a try, as it’s brought to you by the clever folks that make Resharper. Uncle Bob uses it in his series of Clean Code videos as well. I’ve been watching these lately, and his fluency with that IDE is making me long for something a little more… polished than Eclipse. I guess I’m spoiled by Visual Studio.

Anyway, I’ve installed the Community version of IntelliJ. Over the weekend, I spent a few hours porting my home automation project, Daedalus, to be usable by IntelliJ. Mostly, this involved turning it into a Maven project, and then ironing out a handful of miscellaneous details and quirks. I’m already much happier with this IDE than I was with Eclipse.

For starters, the Intelli-Sense (or whatever it’s called) is vastly superior to Eclipse. The static analysis for things like non-compiling code is also much snappier and prettier. And, beyond that, little things do what I’m used to from Visual Studio (e.g. ctrl-tab between code files). It’s weird, but a few things like that here and there really add up to being happier with the user experience. Using IntelliJ feels like coming home, which is impressive, since I’ve never used it (and I don’t even use ReSharper). Color me impressed.

Here is a handful of other miscellaneous observations so far:

  • Ctrl-W and Ctrl-Shift-W widen and narrow selected scope, respectively (equivalent of the numpad + and – in CodeRush).
  • Getting my black background seemed pretty tedious. I didn’t discover until the end that if I set some high level setting with black background, that mostly became default.
  • On the flip side, the color scheme in there is awesome – I can vary RGB ratios and darkness independently, meaning I can keep the default color scheme, but make all the foreground colors a lot lighter so they show up on black.
  • If you download the Community (read: free) version, bear in mind that you get no server integration. It took me a long time to figure out that I couldn’t integrate Tomcat as that’s only for the pay-to-play version
  • The last bullet isn’t a major hindrance. I just set up an Ant build to deploy a WAR file and set the Ant build up to run after successful compile when I want to deploy. The only thing I lose is the ability to start Tomcat in the IDE and browse in the IDE but both of those were pretty flaky in Eclipse anyway. Keeping a browser window open isn’t the end of the world.
  • When I go to commit to SVN, a window pops up with code analysis messages, giving me what I assume is the Java equivalent of StyleCop or FX Cop. This is pretty awesome since my idiomatic Java is pretty rusty. I imagine this will help shake off some of that rust.
  • Still haven’t worked out all of the shortcuts for running tests in TDD. Options seem better than Eclipse, but I still have to tame them.
  • The project/module definition in place of Eclipse’s workspace/project definition is a little odd, but whatever.

That’s about it, so far. I’ll probably have more posts to add as I go. I wish I had documented and blogged about the conversion from Eclipse, as that was relatively straightforward, but with a few gotchas, since I didn’t have Maven set up for Eclipse and I did have the Spring/Tomcat/Jstl dependencies. Thing is, I kind of started off not thinking I was actually going to switch and just doing some exploratory puttering, so I didn’t get into the documentation mindset until it was too late. Oh well, c’est la vie. If anyone’s curious about anything I did, please feel free to comment or shoot me an email.

At any rate, I think I’m probably going to close the books on Eclipse. I suspect that my only future debate here is whether or not to upgrade to the paid Ultimate version of IntelliJ. Given that I alternate between .NET and Java, the relative synergy between IntelliJ and Visual Studio is simply too huge an advantage to pass up. I realize that Eclipse probably has a richer plugin library, but to be honest, my opinion of Eclipse has always more or less been “meh, it works, I guess”, rather than “ooh, this is nice!” After even just a few days with IntelliJ, it’s hard to see myself going back.

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:

Read More

By

JUnit for C# Developers 4 – BDD, Mocks, and Matchers

This is yet another in my series of posts on using JUnit from the perspective of a C# developer.

Goals

Today, I have the following goals in my quest for JUnit TDD proficiency.

  1. Use a BDD-style testing scheme with nested classes.
  2. Use mocking framework to verify method call
  3. Use mocking framework to verify method call with parameters.

Getting to Work

First up, I’d like to see how to employ the test organization scheme described in this post by Phil Haack. The idea is that rather than simply having a test class per class under test, you’ll have a test class and nest within it a sub class for each method in the class under test.

Under Drew’s system, I’ll have a corresponding top level class, with two embedded classes, one for each method. In each class, I’ll have a series of tests for that method.

When you look at this in the test-runner, you see the same descriptive name, but the tests are better organized and can be run at another level of granularity. I’ve come to favor this style when I’m writing code in C#, and I thought I’d see how well it ported to JUnit. As it turns out, the test runner ignores the tests if you simply stick them in sub-classes. I poked around a little and discovered a post by Joshua Lockwood where he had the same idea and found a solution. I tried this out and it got me almost all the way there. I did need one minor tweak, however. (His post was written in 2008, so plenty may have changed in the interim). The “Enclosed” class that he uses required me to import “org.junit.experimental.runners.Enclosed”. By adding this line, I was off and running (though I did have to manually add the import as the IDE didn’t seem to find it):


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.experimental.runners.Enclosed;

import org.junit.Test;
import org.junit.runner.RunWith;
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;

@RunWith(Enclosed.class)
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);
	}
	
	public static class Constructor {

		@Test(expected=IllegalArgumentException.class)
		public void throws_Exception_On_Null_Service_Argument() {
			new LightController((LightManipulationService)null);
		}
	}
		
	public static class light {
		
		@Test
		public void returns_Instance_Of_ModelAndView() {
			LightController myController = buildTarget();
			
			Assert.isInstanceOf(ModelAndView.class, myController.light());		
		}
		
		@Test
		public void is_Decorated_With_RequestMapping_Annotation() throws NoSuchMethodException, SecurityException {
			
			Class myClass = LightController.class;
			Method myMethod = myClass.getMethod("light");
			Annotation[] myAnnotations = myMethod.getDeclaredAnnotations();
			
			Assert.isTrue(myAnnotations[0] instanceof RequestMapping);
		}
		
		@Test
		public void requestMapping_Annotation_Has_Parameter_Light() throws NoSuchMethodException, SecurityException {
			
			Class myClass = LightController.class;
			Method myMethod = myClass.getMethod("light");
			Annotation[] myAnnotations = myMethod.getDeclaredAnnotations();
			
			String myAnnotationParameter = ((RequestMapping)myAnnotations[0]).value()[0];
			
			assertEquals("/light", myAnnotationParameter);
		}
	}
}

Notice the class annotation and the new static nested classes. These nested classes do have to be public and static for the scheme to work. In addition, it seems that once you use the “Run With Enclosed” paradigm, all tests must be in enclosed static classes to run. If you had some defined in the test class itself, the test runner would ignore them.

So, now that organization is better, onto more concrete matters. I now want to use my mocking framework to verify that a method was called. I want to add a method to the controller that takes a room name, a light name, and a text command (“on” or “off”) and issues a command to the service based on that. Using Mockito, I wrote the following test:

@Test
public void calls_service_toggleLight_method() {
	LightManipulationService myService = mock(LightManipulationService.class);
	LightController myController = buildTarget(myService);
	myController.toggleLight("asdf", "fdsa", "on");
		
	verify(myService).toggleLight((Light)anyObject(), anyBoolean());
}

The statement at the end is the equivalent of the “assert” here. I start out by building a mock using Mockito, and then I hand it to my overloaded builder, which injects it into my CUT. I perform (or will perform, since this method isn’t yet defined) an operation on the controller, and then I want to verify that performing that method resulted in a call to the interface’s toggleLight() method. The “any” parameters are known as “matchers” and they can be used in tests not just to see if a method on a collaborator was called, but with what kinds of parameters.

In the C# world, I use Moq and am a big fan of it. If you use this in C#, this whole paradigm should look pretty familiar. We create a mock, inject it, manipulate it, and verify it. Verify here is a static method that takes the mock as an argument, rather than an instance method of the mock, and mock creation is the same, but beyond that, these constructs look very similar, right down to the static “any()” methods for argument matching.

My final goal was to get to the point of using the aforementioned matchers to make sure the service methods were being invoked as I envisioned. To make the last test pass, I wrote the following “simplest possible” TDD code:

public void toggleLight(String room, String light, String command) {
	_lightService.toggleLight(null, false);
}

Since the unit test allowed for any Light object and any boolean to be the parameters, I opted for null and false, respectively. Doesn’t get much simpler than that. To advance my goals a bit, I know that when the command string passed to the method is “on”, I want to call the service with boolean parameter true. So, let’s see how that test would look:

@Test
public void calls_service_toggleLight_with_isOn_true_when_passed_command_on() {
	LightManipulationService myService = mock(LightManipulationService.class);
	LightController myController = buildTarget(myService);
	myController.toggleLight("asdf", "fdsa", "on");
	
	verify(myService).toggleLight((Light)anyObject(), eq(true));
}

It’s a nearly identical test, but this time around, notice that I’ve traded “anyBoolean()” for “eq(true)”. Now this test will only pass if the toggleLight() method calls the service with boolean true. the eq() static method returns a matcher for a specific value. Getting all tests to pass is pretty straightforward here:

public void toggleLight(String room, String light, String command) {
	_lightService.toggleLight(null, true);
}

Obviously, this method is pretty obtuse and needs some work, but I’ll get to that in the “off” command parameter case. The beauty of TDD is that you go from obtuse to rigor and accuracy by adding only the complexity you need in order to satisfy the next requirement. So, to recap, here is the current state of affairs of the controller:

@Controller
@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
	 */
	public void toggleLight(String room, String light, String command) {
		_lightService.toggleLight(null, true);
	}
}

and the test class:

@RunWith(Enclosed.class)
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);
	}
	
	public static class Constructor {

		@Test(expected=IllegalArgumentException.class)
		public void throws_Exception_On_Null_Service_Argument() {
			new LightController((LightManipulationService)null);
		}
	}
		
	public static class light {
		
		@Test
		public void returns_Instance_Of_ModelAndView() {
			LightController myController = buildTarget();
			
			Assert.isInstanceOf(ModelAndView.class, myController.light());		
		}
		
		@Test
		public void is_Decorated_With_RequestMapping_Annotation() throws NoSuchMethodException, SecurityException {
			
			Class myClass = LightController.class;
			Method myMethod = myClass.getMethod("light");
			Annotation[] myAnnotations = myMethod.getDeclaredAnnotations();
			
			Assert.isTrue(myAnnotations[0] instanceof RequestMapping);
		}
		
		@Test
		public void requestMapping_Annotation_Has_Parameter_Light() throws NoSuchMethodException, SecurityException {
			
			Class myClass = LightController.class;
			Method myMethod = myClass.getMethod("light");
			Annotation[] myAnnotations = myMethod.getDeclaredAnnotations();
			
			String myAnnotationParameter = ((RequestMapping)myAnnotations[0]).value()[0];
			
			assertEquals("/light", myAnnotationParameter);
		}
		
	}
	
	public static class toggleLight {
		
		@Test
		public void calls_service_toggleLight_method() {
			LightManipulationService myService = mock(LightManipulationService.class);
			LightController myController = buildTarget(myService);
			myController.toggleLight("asdf", "fdsa", "on");
			
			verify(myService).toggleLight((Light)anyObject(), anyBoolean());
		}
		
		@Test
		public void calls_service_toggleLight_with_isOn_true_when_passed_command_on() {
			LightManipulationService myService = mock(LightManipulationService.class);
			LightController myController = buildTarget(myService);
			myController.toggleLight("asdf", "fdsa", "on");
			
			verify(myService).toggleLight((Light)anyObject(), eq(true));
		}
	}
}

By

Basic Unit Testing with JUnit for C# Developers 2

Last night, I posted about my adventures with TDD in Java from a C# developer’s perspective. As I start to shake my Java rust off a bit, I’m enjoying this more and more, so I think I’ll keep this series going for at least a bit, documenting some of my trials, travails, successes and failures. I don’t know that I intend to turn this into a long-running series, but I’m hoping to throw enough up to get a test-conscious C# developer off and running with Java.

Briefly, Some Good References

So, as part of this adventure, and to get off on the right foot, I’ve been referencing some external information. James Shore has been working on his blog series, “Let’s Play TDD” for over a year now. This is an excellent idea for those trying to get familiar with TDD as a practice. For me, I’m more interested in seeing the simple mechanics of testing in Java, such as where the handiest place to put the JUnit window is. Seriously. It sounds lame, but watching video of someone unit test in Eclipse is incredibly helpful for showing me little details that I’ve been missing and wouldn’t have thought to google.

Another reference is Jakob Jenkov’s tutorial on reflection for Java annotations. If you’ll recall, I mentioned this last time and, as it turns out, this, like many thing in life is possible. So, on that note and without further ado, here’s some code!

And Now For the Code!

	@Test
	public void light_Is_Decorated_With_RequestMapping_Annotation() throws NoSuchMethodException, SecurityException {
		
		Class 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 myClass = LightController.class;
		Method myMethod = myClass.getMethod("light");
		Annotation[] myAnnotations = myMethod.getDeclaredAnnotations();
		
		String myAnnotationParameter = ((RequestMapping)myAnnotations[0]).value()[0];
		
		assertEquals("/light", myAnnotationParameter);
	}

These are two new tests that I added. The first one reflects on the light controller class, seeing if the light() method has an annotation of type RequestAttribute. The second test takes it a step further and sees if the first value of request mapping is “/light” (this is the base URL to which I’m going to map).

And, here is the updated code that this drove:

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

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

All I added was the annotation to light(). And this, unlike the last, more contrived example, I did in true TDD fashion. At this point, I should mention that I found a stack overflow question about whether or not testing for the presence of annotations made sense. Accepted answer seemed to say that it’s fine with a couple of dissenting responses below that.

Personally, as a mild digression, I find the dissent baffling, particularly if those people are familiar with TDD. I’m looking at my light controller class, which needs an annotation to work properly within the Spring MVC framework. It doesn’t currently have one. So… case closed. If I’m following TDD in earnest, I cannot go adding this without a red test. Uncle Bob is pretty clear on this point in his three rules of TDD: “You are not allowed to write any production code unless it is to make a failing unit test pass.” Now, I fancy myself more purist than pragmatist, so the reasoning behind this that speaks to me is that this is a testable alteration I’m making to my class, so why wouldn’t I test it?

Java-Things I’ve Learned

Here are a few random things I learned during tonight’s foray into Java TDD:

  • A more traditional import for asserts is org.junit.Assert.*;
  • “import static” versus just import allows me to use static methods without a qualifying type or being a child class of the class containing the static method. This feels icky to me, like C# extension methods, but I’m grudgingly using it for now with my tests and assert (I may revert to traditional import).
  • Java has a foreach loop: (for myString : someStringArray). During my last go-round with Java, I’m pretty sure that this didn’t exist yet.
  • Java has isinstanceof keyword. For my fellow C# travelers, here is your version of if(x is Foo)

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! 🙂