One unit test with multiple aserts vs multiple unit test with one asserts?

Started by
6 comments, last by Hodgman 10 years, 11 months ago

I have heard multiple theories on this and was wondering if anyone with experience know what works best. FYI, the following code is JavaScript through the idea in general.

There are 2 theories I hear most often on unit testing.

  1. A unit test should only test one logical concept which might include multiple assertions.
  2. There should only be one reason for a unit test to fail therefore there should only be one assertion.

The first one could have a unit test written like:


it('should set default values', function() {
  nagRestSchemaManager.add('user', userModelOptions);
  var model = nagRestBaseModel.create('user');

  expect(model.toJson()).toEqual({});
  expect(model.getDirtyProperties()).toEqual([]);
  expect(model.isDirty()).toBe(false);
  expect(model.isSynced()).toBe(false);
});

The second one could have the same unit test written like:


it('should set json to empty object by default', function() {
  nagRestSchemaManager.add('user', userModelOptions);
  var model = nagRestBaseModel.create('user');

  expect(model.toJson()).toEqual({});
});

it('should set dirty properties to empty array by default', function() {
  nagRestSchemaManager.add('user', userModelOptions);
  var model = nagRestBaseModel.create('user');

  expect(model.getDirtyProperties()).toEqual([]);
});

it('should evaluate isDirty() as false by default', function() {
  nagRestSchemaManager.add('user', userModelOptions);
  var model = nagRestBaseModel.create('user');

  expect(model.isDirty()).toBe(false);
});

it('should evaluate isSynced() as false by default', function() {
  nagRestSchemaManager.add('user', userModelOptions);
  var model = nagRestBaseModel.create('user');

  expect(model.isSynced()).toBe(false);
});

Now I can see the arguments for both. The first requires less code to be written. The second will quickly test you what is failing (with the first you would have to go into the code to see the exact failing reason).

My question is, in practice, is one generally preferred over the other?

Advertisement

If you look at the unit tests in the code for my recent article, you'll see I tend to go with the 'concept' driven unit tests and avoid the single assert/test pattern. My theory is that a single assert per function doesn't mean a single possible point of failure anyway, so I may as well test all related bits and assert each one as I go. It's a chicken and the egg problem, if you have to test the constructor, how do you test it without using other potentially failing items? In the SIMD code for instance, the constructor could out right crash and throw a failure due to data missalignments, bad instructions etc. But even if the data successfully constructs, that means nothing unless I check that what I put into the class is the same as what I can get out, i.e. I need to use some form of accessor to validate the result. So, even if I split everything up as much as possible, I still have two potential points of failure and for a multitude of different possible failure reasons.

To me, if I know I have two or three possible points of failure just to get to the test item, I might as well insert the extra asserts along the way. Additionally, in the case of accessors for instance, I'll test x/y/z accessors all in a single place. I tried the single assertion pattern and it simply provided me with no benefits and actually a considerable amount of hassle when I was fiddling with interface changes.

Obviously this is opinionated, so take it with a grain of salt. :)

I'm pragmatic about this. If your Unit Test has a lot of asserts, it's probably not a Unit Test, and is likely a component test of some kind. I'd say as a rule of thumb, I like to keep my asserts under 5 (with the ideal being 1) for a given set of inputs to a test. In your example, I'd say the first was fine - but I wouldn't want to go much higher on the assert count.

The first one is better, I think.

I just view those multiple expectations as a single assertion split into multiple lines for convenience.
Really, you're just testing the value of model as though this pseudo code worked:

expect(model).toEqual(defaultModelValue);


More importantly, unless you're following TDD or are very disciplined, you have to weigh up how likely you are to write a given unit test - the first example is quicker and easier to write and therefore more likely to get written. Unit tests that actually exist, even if they're less than perfect, are better than nothing.

Unit tests that actually exist, even if they're less than perfect, are better than nothing.

Score 1! :)

I like pragmatic and I tend to do TDD. But, I only go so far when folks suggest strict rules. I'm testing a cross product, I'll pack as many asserts into the 'test' as needed to make sure the cross product is valid, I don't see a reason to split x vs y into a separate test to y vs x which simply has a negated Z for all the same input data. To me, it is a hell of a lot of extra typing even though the assertion is identical other than negating one element. Silly extra typing for no good reason is my thinking.

I think what tends to happen for me is that the number of things tested in each test depends on how expensive the setup is.
If each test is cheap to set up then I test very little in each method.
If the test is expensive to set up, then I test several things in each method.

It's a happy compromise.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

While I would prefer the first, I will say one thing that leans toward the second: the second one seems more verbose in its output, seeing as it has a string provided for it that explains what needs to be tested. The first seems more ambiguous than the second, because it doesn't appear to have the human-readable information associated with it; sometimes seeing a value and maybe a variable name isn't good enough to know what was trying to be accomplished there. So, I'd only vote for the second since it provides a greater amount of information to the developer.

However, back to the first, I use a system that has human-readable strings as a parameter to the string, so the text is output during the assertion if enabled; it has the simplicity of the first, with any verbosity benefits of the second.

I have a hierarchy that may or may not be common. I have a test harness for a given component, which then has member test functions that test each individual operation provided by the component, and in each function is any number of assertions testing everything to make sure that the operation in question is performing all of its tasks. I tend to test related functions within the same test function, like overloads of the same operation for slightly different data types.

In regard to the chicken and egg situation, I construct with some test vectors, and check if the accessors return expected values. It requires a little faith in the middle the two, but for objects where you can't tell if it failed construction without using accessors, there isn't much you can do. On the bright side, if it breaks right off the bat, you have relatively few places to check: that accessor, or the constructor. So, I would break into the debugger in between the two, and manually verify that it is constructed properly, dividing the work in half. This is an obvious approach, but my point is, it isn't always a problem when you have to group together functionality that depends on each other. Often, it is a good choice.

All code that you write should be chock full of assertions. So, even if a unit-test only contains a single explicit assertion, the code that it is testing might have 100 internal assertions that are also implicitly being tested... which means that counting the number of assertions isn't really a meaningful statistic, and you're back to just using common sense about which "unit" of code you're testing.

With your examples, you can move the descriptive string from the it function to the expect function, and it fixes your concern, and makes both approaches exactly equivalent, where there's no choice/dilemma any more ;)

This topic is closed to new replies.

Advertisement