• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
3dmodelerguy

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

7 posts in this topic

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?

0

Share this post


Link to post
Share on other sites

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. :)

0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites
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:

[pre]expect(model).toEqual(defaultModelValue);[/pre]

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. Edited by dmatter
1

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

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.

0

Share this post


Link to post
Share on other sites
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 [tt]it[/tt] function to the [tt]expect[/tt] function, and it fixes your concern, and makes both approaches exactly equivalent, where there's no choice/dilemma any more ;)
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0