Autofixture: Do() not working? You forgot Without()

I use AutoFixture for generating test data in my unit tests. AutoFixture has served me well, but the documentation doesn’t give great examples of how to use it. The “cheat sheet” has links to the authors blogs, and if you’re not careful you won’t find everything you need. It’s sometimes easy to miss those links.

The other day, I was trying to generate a POCO that had a string property, and I wanted that string property to be constrained to a list of valid values. Since I obviously didn’t want to customize the string type across my entire fixture, I instead customized the parent type with the Do method. I wanted to pass in an action that would randomly select from the list pre-defined values and then assign it to the string property in my class instance. The code was straight-forward, but the string was still being populated with the default AutoFixture value.

Read more »

Using delegates for loose coupling and easy unit testing

In a typical ASP.NET MVC or WebApi project, controller actions often do nothing more than make a service call, map the returned domain object to a view model, and either render a view with the model or simply return it for the framework to serialize as JSON. Using AutoMapper, a simplified WebApi controller action may look something like

public EmployeeViewModel GetEmployee(string employeeName)
{
  var employee = _employeeService.GetByName(employeeName);
  var viewModel = Mapper.Map<EmployeeViewModel>(employee);
  return viewModel;
}

This is a pretty common but difficult to test pattern because of the static Mapper dependency. You can’t actually unit test the controller action without having a properly (or at least minimally) configured static Mapper. New versions of AutoMapper provide different ways to solve this problem, like the injectable IMapper interface, but I want to demonstrate another method to reduce coupling and ease unit testing.

In this entry, I’ll demonstrate how to get rid of the static Mapper dependency without using the IMapper interface, which exposes several overloads to map one data type to another, or creating your own interface that serves a similar purpose. Instead, we’ll inject a delegate whose signature is very expressive.

public delegate TDest MapperFunc<in TSrc, out TDest>(TSrc source);

Read more »

If Akka.TestKit.NUnit tests are not running, check your package versions

As of this writing, Akka.TestUnit.NUnit and NUnit 3 are incompatible with one another. Specifically, package version 1.0.5 and NUnit 3.0.1. I’ve opened an issue with the Akka.net team (Issue 1651) so you can watch it for the resolution to this problem.

I was trying to test Akka.net actors in a project that was already using NUnit 3.x. I wrote the tests, but when I ran them with the ReSharper test runner, they would show up for just a split-second and then disappear. I thought that maybe it was the ReSharper test runner since that very day I had to upgrade from R# 9 to R# 10 to get the NUnit 3 support. I tried running the tests from the NUnit 3 console runner and experienced the same thing, though. The tests weren’t failing or marked ignored, or even “not run”, the test runner just didn’t pick them up at all. With a little help from the good folks at the Akka.net Gitter chat, I was able to get my tests running by downgrading to NUnit 2.6. I suppose it is a “known” issue but maybe not that well known since there was no issue logged for it ?

Replace switch statements with dictionaries

I don’t care for switch statements in C#. They’re a poor substitution for pattern matching. They require a compile time constant like a string, an enum, or an integral. Because of that restriction, they are not even a good replacement for giant if-else constructs, which was their intended purpose. On top of all of that, their syntax is ugly and error-prone. Ever left out a break; and saw some unintended consequences due to the fall through?

In general, I regard switch statements a code smell. Usually, some factoring could remove the need for them completely. However, there are times when you just have to make due with switch statements, like you’re on a tight deadline so refactoring is out the question, or maybe there just isn’t a good way to refactor it out of existence. If you’re stuck with a switch statement, there may be a better solution. Let me show you how to turn ugly switch statements into something more manageable.

Read more »

Should, ShouldBe; a silly mistake using FluentAssertions

I use FluentAssertions for all of my asserting needs. I like it’s API better than the assert methods you get with the .Net framework, and the FluentAssertions library provides an overall more fully featured set of assertion options. It’s open-source and continually updated, too, which makes it all right in my book. Sometimes, though, while I’m furiously writing tests, I get this test failure signature and it catches me off guard.

Subject has property Subject that the other object does not have.

Here’s a sample NUnit test case that would cause this particular error.

internal class MistakesTests
{
    [Test]
    public void ThisDumbThingIKeepDoing()
    {
        var thing = new Thing { FirstName = "Nelson" };
        var thing2 = new Thing { FirstName = "Nelson" };
        // This should definitely pass, right?
        thing.Should().ShouldBeEquivalentTo(thing2);
    }
    private class Thing
    {
        public string FirstName { get; set; }
    }
}

As you can see, I’m just doing a very simple object graph comparison, but it isn’t working as I intended. Can you spot the error?

Whereas I should be calling ShouldBeEquivalentTo on my Thing instance, I’m actually calling it on an instance of ObjectAssertions type from the FluentAssertions library. Whoops! ?

Sometimes, you should just go look

Fair warning: I shamelessly stole this story from a colleague.  Let’s call him Jimmy. He doesn’t have a web presence though, and I think it’s worth sharing.

Jimmy was working on a web application. This particular web application had a feature that only activated on a double-click.  Don’t be too harsh on Jimmy; he didn’t have a choice in the matter. Sometimes, you have to do what you have to do.

A user, let’s call her Sandra, was having trouble with this particular feature and was having trouble communicating why. A ticket would come into Jimmy’s work queue with a description akin to “it don’t work [sic]” and nothing else. Jimmy tried his best to recreate the problem with no success. Every browser that the company officially supported seemed to work correctly with the Javascript responsible for identifying a double-click.  He sent the ticket back to Sandra looking for more information.

Somehow, the ticket bounced back and forth between the two a few times with no suitable reproduction steps, and Jimmy was at his wit’s end. After several code re-writes and testing across both supported and unsupported browsers, Jimmy gave up and asked Sandra if he could see the problem in action.  Once he found Sandra’s desk, he asked for a demonstration.

Sandra brought up the UI and found the feature in question.  Jimmy was bristling with excitement, at least until he saw the problem.  Sandra hovered her cursor over the button in the UI and clicked with fierce tenacity. A moment later, and no sooner, she clicked again, with equal tenacity.  A wry grin must have crossed Jimmy’s face as he explained the difference to Sandra between a double-click and two clicks in succession.

If you learn nothing from my posts, learn these two lessons:

  1. Never put a double-click event in a web app
  2. Walk to the user’s desk to identify mysterious problems that only they seem to have

Know thy shell, or why dig wasn’t working in PowerShell

An application I work on utilizes DNS for important aspects of its functionality.  The other day, I wrote a quick and dirty command line application to write zone files for a static set of domains.  The app would allow a developer to double-click an .exe and set up a known set of domains in a local Bind instance for test purposes without having to know how or take any manual steps. It was a one-time-per-developer app so I didn’t put a lot of thought or time into it.

Or, at least, I didn’t mean to put a lot of time into it.  I ran the executable which wrote the zone files, restarted Bind, and ran the following command in an already opened PowerShell terminal to verify that my test domains were being served by my local Bind instance.

PS C:Bindbin> ./dig @localhost ns1.dnstest.dev.local
; <<>> DiG 9.9.4-P2 <<>> ns1.dnstest.dev.local
;; global options: +cmd
 ;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 45832
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1280
 ;; QUESTION SECTION:
;ns1.dnstest.dev.local.        IN      A
;; AUTHORITY SECTION:
dev.local.           3600    IN      SOA     dev-ad-01.dev.local. hostmaster.dev.local. 6876 900 600 86400 3600
;; Query time: 4 msec
;; SERVER: 10.0.5.2#53(10.0.5.2)
;; WHEN: Tue Feb 18 18:09:52 Central Standard Time 2014
;; MSG SIZE  rcvd: 131

status: NXDOMAIN in the answer section of the response means the DNS query failed. What gives? Now, if you are a seasoned PowerShell user, you probably already see the problem. As a PowerShell novice at best, I did not. Read more »

Don’t throw exceptions with internal constructors

I ran into an annoying problem the other day when working with a 3rd party library, mail.dll.  You see, mail.dll exposes library methods for sending email messages to an SMTP server, functionality common enough that you should never have to write it yourself.  While I’ve been pleased with its ability to perform SMTP conversations, I have not been impressed with its use of exceptions.

When the mail.dll SMTP library fails to connect or get a response from the SMTP server to which it is connecting, it throws a mail.dll-specific custom exception, SmtpResponseException.  Likewise for the IMAP and POP3 libraries, if a failure happens during client interaction with the server, an ImapResponseException or Pop3ResponseException is thrown, respectively.  Since, in the normal course of a properly configured mail client’s operation, the expectation is that the server will respond appropriately, I don’t have a problem with these libraries throwing exceptions.  They are understood and can be handled by the consuming application.

Here’s the annoying bit. The custom exceptions thrown by mail.dll only have internal constructors and cannot be thrown outside of the mail.dll assembly.  In this article, I’ll talk about why your library should not throw exceptions that the consuming code cannot throw itself and a workaround when someone else’s library does.

Read more »

Freecell is a good distraction

Hey, 3 out of 4 ain’t bad.

freecell_stats

Two reasons your MarkLogic code is failing silently, part 2

Silent failures are a programmer’s worst nightmare, and in a world where first class debuggers are few and far between, those silent failures are sure to drive us crazy.  In the first half of this article, we discussed silent failures in MarkLogic due to XML namespace issues.  XML namespace issues are going to crop up in any implementation of XQuery, though, so there are many resources to reference in addition to my article.

In the second (and last) part of the article, we’ll discuss a feature specific to MarkLogic’s XQuery implementation.  This feature is called function mapping.

Read more »

The Benefits of Online Virtual Data Rooms in Business Deals

In the fast-paced world of business deals, managing and exchanging sensitive information efficiently and securely is crucial. Online virtual data rooms have emerged as indispensable tools for businesses. On https://data-rooms.org/, we will explore the numerous benefits that online virtual data rooms offer in facilitating seamless and secure business deals.