Tag Archives: Developer

How to Write Unit Tests in .NET

Unit testing is the idea of writing a separate set of code to automatically execute your production code and verify the results. It’s called a ‘unit’ test because the idea is that you are only testing a single ‘unit’ of code and not the entire application. Writing Unit Tests is often seen in Test Driven Development but can and should be used in any development environment.

Unit tests give your application increased testing coverage with very little over-head. Most unit tests can execute extremely fast which means you can write hundreds of them and execute them all relatively quickly. In environments with multiple developers, unit tests can provide a sanity check for other developers making changes to existing code. But how do we actually go about writing a unit test?

Advertisements

In .NET there’s a couple of ways we can do this. In Test Driven Development, you write your tests first. That sounds backwards but it’s really about teaching your mind to think a certain way before you start writing any code because to write unit tests, you need highly decoupled code with few dependencies. When you do have dependencies you’ll want to use Dependency Injection (which we can cover at another time).

The .NET stack provides a built in testing harness called MSTest. It gets the job done but doesn’t come with the bells and whistles. I personally prefer xUnit which can be downloaded as a Nuget package. There is also NUnit which is very similar but I prefer xUnit because each execution of a test is containerized where as in NUnit all tests are run in a single container.

So once we’ve installed xUnit we can start writing our first tests. The first thing to do is to create a new project in your solution. We can do this by opening up our project in Visual Studio and then right-clicking on our solution, choosing Add, and then new project. From the ‘Add a new project’ window we can search for ‘xUnit Test Project‘ and add that. I simply name the project ‘Test’ and click create.

Advertisements

By default a new class is created which contains your new test class. You should also see the ‘Test Explorer’ window in Visual Studio on the left-hand side. If you don’t, go to the ‘View’ menu and select it. This menu contains all of your tests that you write and allows you to run them all or run them individually. You can also kick off a single test to debug it.

Now the fun part, writing a test! Let’s keep it simple for starters and look at an example test:

[Fact]
public void ItCanAddTwoNumbers()
{
   var result = AddTwoNumbers(1, 4);
   Assert.Equal(5, result);
}

So this test is doing a couple of things. By defining [Fact] we are saying this function is a test function and not some other helper function. I try to name my test functions based around what the application is trying to do like, ‘ItCanAddTwoNumbers’ but that is completely up to you.

Within the test function we can then call the function we want to test which in this case is ‘AddTwoNumbers(int num1, int num2).’ Simply calling this function and making sure the application doesn’t crash or throw an error is already a little bit of test coverage which is great, but we can go farther. We can not only make sure it doesn’t error, we can make sure we get the right results back.

We can do this using ‘Assert‘ which gives us some different options for verifying the results are correct. In this case, our test will check to make sure the ‘result’ variable does equal 5. If it does, our test will pass with green colors. If not, our test will fail and show red in our Test Explorer. This is great when you already have some test written, you make some code changes, and then re-run all of your tests to make sure everything is still working correctly.

One last tip, instead of using [Fact] we can use [Theory] to allow us to pass in multiple test values quickly like this:

[Theory]
[InlineData(2)]
[InlineData(5)]
[InlineData(7)]
public void ItCanAddOneToANumber(int number)
{
    var results = AddOneToNumber(number);
    Assert.Equal(number + 1, results);
}

Hopefully this gives you a brief introduction into how to write Unit Tests in .NET using xUnit. Unit testing will save you hours of debugging and troubleshooting time when that sneaky bug shows up that you can’t quite track down. Even if the bug is not in your unit tests, it can help you track down the issue faster because you’ll know it’s not in any of your code that you have unit tests for.

Always test and happy coding!

How I Conduct a Code Review

Code reviews have been and always will be tricky business. If you’re familiar with performing code reviews or having someone else review your code, you hopefully can understand and see the benefits. For some though, a code review can be a hit to the ego. Here’s how I’ve approached code reviews and what I find works best.

First and foremost, you have to have some formal code review practices in place. If you don’t, I suggest you start by offering up your services. Not in a way that says, “I’m a better developer and I know more so let me make sure your code is right.” If you give off any type of vibe like this, your code review is going to come off as arrogant and unwanted.

Offer your services for a code review as a means to help take some of the pressure off of the other developer. Your code review is to help them look for bugs, typos, or little details they may have missed. It’s also to provide a challenge back to that person to ask both you and them to think critically.

Once you’re able to agree to a code review with your peer, the next step is actually conducting the review. But how do you go about performing a code review? What should you be looking for? What really works? I follow these same steps, every single time, and find they always hit the nail on the head.

Advertisements

Step 1: Compare

Before I actually do any real review, I start by performing a compare. There are a lot of ways to compare the changes, before and after, and I’ll let you figure that part out. I start with a compare to get a sense of what I’m going to be reviewing.

How much code has changed and how much did it change by? At times I may find that too much has changed, making the review nearly impossible. When this happens, it’s best to recommend that the developer try to create smaller commits. BOOM! You just gave your first piece of code review feedback.

When looking through the compare, don’t try to focus on individual lines of code yet. We’re not at that stage. Stay at a high level and focus on structure and getting familiar with what you’re working with. Are there new classes or functions? Is it a complete rework or just a quick change? Are there unit tests? Did the developer leave any notes for the reviewer? Focus on gathering information and making an initial assessment.

If I suspect that the developer is not done working on an area or that there may be major, additional changes I will stop my review right there on that area. There is no sense in going to the next level of review if the section of code will potentially be refactored or changed. Save yourself some time and simply give the developer your high level assessment and tell them you look forward to diving deeper once they are closer to completing their changes.

photo cred: Pankaj Patel

Step 2: Debug

This is a step I think a lot of inexperienced code reviewers skip over. DEBUG THE F%$*@!+ CODE! For real though, pull the code down, set breakpoints on all of the changes (because you know where they are because you just did a before and after compare on them) and start to debug. I find that it helps me if I just go line-by-line and get an understanding of what each piece is doing.

This is where I really start performing the review. I look for any errors, bugs, or design flaws. I also ask questions about anything I’m unfamiliar with myself. If the developer created Unit Tests I try to either add my own data to those tests or see if I can break them. This helps expose any areas the developer over-looked.

You might be thinking that stepping through each line is not needed or that it’s a lot of extra work but in all honesty it’s not. You can debug a few hundred lines of code in a matter of minutes. Most developers break things out into more lines than what they would ever really need and stepping through that code becomes even easier.

photo cred: Agence Olloweb

Step 3: Feedback

After stepping through every line of code you should be prepared to provide your feedback. When it comes to feedback I find there is really only one good way to do it. Keep it positive and make it suggestive. At the end of the day, the developer who wrote the code has to be responsible for the quality of that code. Often times if you try to force a change in your code review you’ll end up with a You vs Me scenario that isn’t really productive for anyone.

I prefer to start with something positive. I try to take into account the amount of time and effort the developer had to put into their work and look for any design patterns or usage of good programming practices that I can point out right a way. It’s a lot more fun to code review someone’s work when they are using best practices.

For the harder stuff, I try to offer up changes as a suggestion. Unless I see a clear cut bug. If I see a bug or true flaw I try to provide a Unit Test or solid steps to reproduce to help the developer out. After all, we’re all in this together.

If the change is more about design or best practice, then I offer it as a suggestion. I might say, “Hey you could try this technique here to reduce x amount of code” or “If you try this, it can help keep things easier to maintain down the line. Let me know if I can help!” Offering up additional services or help is often a great way to provide feedback.

Advertisements

Step 4: Rinse & Repeat

From there you can send your code review back. Try to capture as much as you can in that first review. It’s much less grueling if you have to go back-and-forth and back-and-forth because you keep only catching one issue at a time. Try to capture all of it, up front, on the first review.

When the code comes back again for a second review. Hopefully all items are addressed and you can pass the review BUT don’t be afraid to go back through steps 1-3. Actually I encourage you to go through them each time, just maybe at a faster pace or a high level. For example, your first pass you should debug every line of code, maybe on your second review you just stick to the areas of change.

Hopefully this gives you a good idea of how to conduct a code review! If you have any personal tips on your best practices for code reviews I’d love to hear them!