Methodology
Don’t Moq it Up
0So today I was going through my regular google reader list and came up Hadi Hariri’s Blog post on how to use mocking to unit test your controllers. Here is the post. I was reading it and thought it was a great way to use Moq and the right way to use Moq. If you are using Moq, you should read that post.
I’ve realized like any other tool, you need to use Moq sparingly or else your unit tests will become hellishly difficult to manage. So how do I unit test today? I unit test by getting back to basics.
Virtual Is Your Friend!
I’m sure this isn’t big news to anybody, but protected virtual is the best way to unit test your code. If you start yelling at me about code smell then I implore you to look at any of the fancy ORM tools you are using. They all use virtual to sneak in dynamic proxies and do what I am about to show you.
So you have a controller / class that has some strange external dependency and you just need a single value from this dependency. You don’t want anything more than a string value. Let’s look at what we have below.
public class HomeController : Controller {
public ActionResult Index() {
var urlReferer = Request.UrlReferer;
return View("Index", new { urlReferer = });
}
}
Oh jeez, what are we going to do about that Request object? We could use Moq and get into a mess, or we can look at what we are actually trying to do. We just want the UrlReferer. So let’s do that, we will just get that value. Time to refactor.
public class HomeController : Controller {
protected virtual string UrlReferer {
get { return Request.UrlReferer; }
}
public ActionResult Index() {
return View("Index", new { urlReferer = UrlReferer });
}
}
Notice we moved the UrlReferer into its own property and we reduced the size of our index method. Next step is to write our unit test. I Use XUnit, but you can use any framework you like since there is no dependency on any particular library.
public class HomeControllerTests {
[Fact]
public void Can_test_home_index() {
var test = new TestHomeController() { TestUrlReferer = "http://www.google.com" };
var value = test.Index();
Assert.IsNotNull(value);
}
public class TestHomeController : HomeController {
public string TestUrlReferer {get;set;}
protected override string UrlReferer { get { return TestUrlReferer; } }
}
}
We have to inherit from HomeController and create a TestHomeController class. We override the UrlReferer property to inject our test value. Our final step is to write our unit test without having to worry about a crazy mocking library getting in the way.
The nice thing about this method is you can use it for any external dependency and it will always work. It also keeps your tests clear and doesn’t add a lot of overhead to your original classes. So go forward and unit test, and don’t let mocking get in your way.
Must Have NuGet Packages
2I am loving NuGet, and as it matures it just becomes more of a paradigm shift. How do you program without this thing? What was development like before it? So what are NuGet packages I am usually including in my projects. Here is a list of the them below, in no particular order.
- Depot (Common Caching)
- Dynamic Expression API (LINQ Extensions)
- ELMAH on XML (Error Logging)
- FileDB (a leap in storing files)
- SimpleMembership
- ValueInjecter
- WebActivator
- RhinoETL
- FluentMigrator
- RestfulRouting
- JQuery
- FluentValidation
- Entity Framework Code First
- NUnit
- Moq
- WaTin
- RestSharp
- MvcFlash (yes I am bias
)
Great respect goes out to these projects and their contributors, except MvcFlash cause I don’t want to strain my arm patting myself on the back
.
Update: How could I forget about MvcMailer.
Git –newbie –workflow
1Introduction
I recently found the time to dedicate to learning a distributed version control system. I had the choice between Mercurial and Git. Both are great systems but what it came down to ultimately was the fact that I already had TortoiseGit on my machine. Yes you read that right, it came down to the fact that I didn’t want another source control provider taking up space in my context menu; frankly my context menu is getting a little ridiculous.
I know it isn’t exactly a scientific method of picking between the two, but honestly, I see very little that is different between the two (for a learner).
Initial Reaction
When I first read the description of Git, I thought “who would be stupid enough to have source control on their own machine?” The second thought to go through my SVN-centric brain “I like SVN, so why should I change to Git?” The first question came out of ignorance to the ideas behind a distributed source control system, the second is a completely valid rebuttal.
I will attempt to address the first question. Yes your source control is on your machine but think of it as your own personal local copy of the “Truth.” You edit your version of the “Truth” until you feel comfortable with your additions and changes. The next step is to push your changes to a central version, possibly on GitHub or Unfuddle. That last step is important, because your source is no longer local. Your code now exists somewhere that is hopefully safe, secure, and accessible to you and your team of developers. What is powerful about Git is the fact that most of the expensive actions performed locally: commits, merges, additions, and deletions. This makes Git crazy fast, CRAAAAZZZY FAST! The two most expensive actions are pull and push, but even these can be quick if your central source control repository is on the local network. After a couple hours playing with Git, my ignorance about the ideas behind this system were overcome by an understanding and comfort.
The second question is valid. If you like SVN, why should you switch? Well nobody is forcing you to switch, and people won’t call you a loser if you decide to stick with SVN. I still have a warm place in my heart for SVN, it was the Han Solo of my escape from the Death Star known as VSS (Visual Source Safe). That being said, Git is a lot easier when it comes to branching and merging. In SVN branching occurs remotely on the SVN repository, which can be slow. In Git, branching happens locally and is even encouraged by most resources that I read. The one thing developers might gripe about Git is the fact that there really isn’t much Visual Studio integration. SVN has a ton of integration tools inside Visual Studio. What I would say about this though, is that the projects I work on have more than enough files outside of my VS Solution to negate the good aspects of integration tools. File types like third party assemblies, documentation, build scripts, and other files all exist outside the scope of my solutions. Now to add them to your SVN repository you are forced to use TortoiseSVN, a tool that exists outside Visual Studio.
I may or may not have convinced you to try Git, but I really feel you should. More and more compelling projects are being hosted on GitHub. How will you get involved and help these projects grow with a knowledge of Git? Also, Codeplex now offers Mercurial support, so don’t be suprised when your favorite projects on Codeplex start moving to a distrubuted SCM.
Basic Workflow
To get started with Git download MsysGit. This will setup an environment ready for Git on your windows machine.
I also recommend TekPub, they have a great series about mastering Git.
To learn about a system you have to use it, and that is what I did with Git. I wouldn’t call myself an expert but I do feel comfortable enough with it now to jump into a Git project. The basic Git workflow is as follows (type: “git help” in a command window):
- init or clone: if you are starting a repository use init, if you are getting use clone.
- branch: create a new branch to start working in or just work in the master branch.
- add: add any or all files involved in your project.
- commit: commit staged files to your local source repository.
- pull: get any changes that have occurred at the central repository.
- merge or rebase: make sure all your changes and branches are reflected in the master if need be.
- patch or push: some repositories online are private so you can produce a patch to send to the owners, if you own the repository the push away.
- Rinse and Repeat until content.
These are the commands you’ll need to know to just get by, but there are many more to become a master. I modified my environment to work with WinMerge for both merging and diffing. Below are the instructions to get that working.
- You will need to modify your git environment. This is done through modifying the .gitconfig file found in your user folder (C:\Users\<yourname>\.gitconfig).
*Note, when you install WinMerge be sure to check the box that installs WinMerge into your system path.
external = “c:/users/khalid abuhakmeh/difftool.sh”
[merge]
tool = winmerge
[mergetool "winmerge"]
cmd = ‘WinMergeU.exe’ \”$MERGED\”
trustExitCode = false
keepBackup = false
- Create a bash script to execute against WinMerge. Create a file called difftool.sh and save it in the same directory. Below are the contents of my file.
#!/bin/sh echo Launching WinMergeU.exe: $1 $2 "C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -ub "$1" "$2" | cat #!/bin/shecho Launching WinMergeU.exe: $1 $2"C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -ub "$1" "$2" | cat
Now when you execute the commands "git diff @{1}" (compares against previous version) or "git merge" you will get to use WinMerge to perform those actions. Pretty cool.
Conclusion
So there you have it, my initial interactions with Git and what I have learned so far. There are more things to learn, but I am definitely a convert to Git. Can you Dig Git?
DDD, BDD, TDD…. What’s the Difference?
1For me software development has become more than just writing code, although ultimately that is what it’s about; a developer writing applications that work and serve a function. As I’ve progressed through my development life, I have picked up techniques and methodologies to help me develop a better application. Some of these techniques are Domain Driven Design (DDD), Behavior Driven Development (BDD), and Test
Driven Development (TDD). Jeez that’s a lot of D’s! What’s the difference between all of these methodologies and when to use them? Well I’m about to tell you where they fit into my development ecosystem. Again, this is where I’ve found these methodologies to work the best for me.
Domain Driven Design (DDD)
I’ve always thought of DDD as a mindset rather than a code writing methodology. DDD’s main focus is create a dialogue between developers and the domain they are attempting to develop in. For example, if I were writing a blog, then my discussions and inevitably my code would include words like “posts”, “tags”, and “categories”. I’ve always found DDD to be easy for developers to understand. It doesn’t require any tools except for a good whiteboard and some developers willing to talk to each other and their business partners. Below are the necessities that I perceive to properly implement DDD.
DDD Necessities:
- Whiteboard
- Open dialogue
- Domain experts
- An open mind
Behavior Driven Development (BDD)
I use BDD to express my application’s intent (with code) within my project. The specifications are written using stories and scenarios, and it is my job to make sure that those stories are true through functionality. BDD is cool because intentions are visible, and all your BDD stories are written in English that is understandable to your domain experts. BDD and DDD are tightly interlocked because your stories will most likely come out of your DDD sessions with your domain experts. Below are a overview of the tools needed to implement BDD.
BDD Necessities:
- BDD Framework (For .Net : MSPEC, StoryQ, SpecUnit.Net, SpecFlow)
- Story (Test) Runner
- Discipline of Steel ( the most important thing)
Test Driven Development (TDD)
I still use test driven development, but in a different scope. TDD has turned into my debugging approach of choice when dealing with a client’s code. I attempt to write a unit test to isolate issues. During this process, I can re-factor and learn more about the newly presented code base. Once I can reproduce the bug through a unit test, I can start thinking about what I need to do to solve the issue. This method of debugging only works with code based bugs, and not things like memory leaks.
TDD Necessities:
- TDD Framework (For .Net : NUnit, xUnit, MbUnit)
- Test Runner
- Ability to reverse engineer
Conclusion
As you see above, all these methodologies are alive and well in my development ecosystem and they all play overlapping roles. The thing to keep in mind is that there isn’t a point where I say “I am going to do BDD now!” or “It’s time for some DDD!” These methodologies are applied fluidly but precisely. I cannot stress enough that self discipline is at the foundation of any methodology you use. If you don’t believe enough in the methodology to follow it’s main tenants, then you’ll find yourself undermining your own efforts. At the end of the day, a methodology is a system, a series of steps that you take to develop an application; respecting that system can yield great results.


