DEV Community

CodingBlocks

Episode 54 – Clean Code – How to Write Amazing Unit Tests

When and why should you write unit tests, and just how important are they? Take a listen and see what YOU think.

#yop-poll-container-31_yp58cf5c30bed76 { width: 1000; background:#fff; padding:10px; color:#555; overflow:hidden; font-size:12px; } #yop-poll-container-31_yp58cf5c30bed76 input[type='text'] { margin:0px 0px 5px 0px; padding:2%; width:96%; text-indent:2%; font-size:12px; } .yop-poll-name-31_yp58cf5c30bed76 { font-weight:bold; background:#327BD6; color:#fff; padding:5px; text-align:center; font-size:12px; } #yop-poll-questions-container-31_yp58cf5c30bed76 { font-size:14px; margin:5px 0px; } .yop-poll-question-container-31_yp58cf5c30bed76 { padding: 2px; } .yop-poll-question-31_yp58cf5c30bed76 { background:#327BD6; color:#fff; margin-bottom: 21px; margin-top: -10px; font-style: italic; text-align: center; width: 100%; padding:5px; } .yop-poll-answers-31_yp58cf5c30bed76 { } .yop-poll-answers-31_yp58cf5c30bed76 ul { list-style: none outside none; margin: 0; padding: 0; } .yop-poll-li-answer-31_yp58cf5c30bed76 { font-style:normal; margin:0px 0px 10px 0px; padding:0px; font-size:12px; margin-bottom:20px; } .yop-poll-li-answer-31_yp58cf5c30bed76 input { margin:0px; float:none; } .yop-poll-li-answer-31_yp58cf5c30bed76 label { margin:0px; font-style:normal; font-weight:normal; font-size:12px; float:none; } .yop-poll-results-31_yp58cf5c30bed76 { font-size: 12px; font-style: italic; font-weight: normal; margin-left: 15px; } .yop-poll-customs-31_yp58cf5c30bed76 { } .yop-poll-customs-31_yp58cf5c30bed76 ul { list-style: none outside none; margin: 0; padding: 0; } .yop-poll-li-custom-31_yp58cf5c30bed76 { padding:0px; margin:0px; font-size:14px; } /* Start CAPTCHA div style*/ #yop-poll-captcha-input-div-31_yp58cf5c30bed76 { margin-top:5px; } #yop-poll-captcha-helpers-div-31_yp58cf5c30bed76 { width:30px; float:left; margin-left:5px; height:0px; } #yop-poll-captcha-helpers-div-31_yp58cf5c30bed76 img { margin-bottom:2px; } #yop-poll-captcha-image-div-31_yp58cf5c30bed76 { margin-bottom:5px; } #yop_poll_captcha_image_31_yp58cf5c30bed76 { float:left; } /* End CAPTCHA div style*/ .yop-poll-clear-31_yp58cf5c30bed76 { clear:both; } #yop-poll-vote-31_yp58cf5c30bed76 { } /* Start Result bar*/ .yop-poll-results-bar-31_yp58cf5c30bed76 { background:#f5f5f5; height:10px; } .yop-poll-results-bar-31_yp58cf5c30bed76 div { background:#555; height:10px; } /* End Result bar*/ /* Start Vote Button*/ #yop-poll-vote-31_yp58cf5c30bed76 div#yop-poll-vote-31_yp58cf5c30bed76 button { float:left; } #yop-poll-vote-31_yp58cf5c30bed76 div#yop-poll-results-31_yp58cf5c30bed76 { float: right; margin-bottom: 20px; margin-top: -20px; width: auto; } #yop-poll-vote-31_yp58cf5c30bed76 div#yop-poll-results-31_yp58cf5c30bed76 a { color:#fff; text-decoration:underline; font-size:12px; } #yop-poll-vote-31_yp58cf5c30bed76 div#yop-poll-back-31_yp58cf5c30bed76 a { color:#555; text-decoration:underline; font-size:12px; } #yop-poll-vote-31_yp58cf5c30bed76 div#yop-poll-archive-31_yp58cf5c30bed76 a { color:#555; text-decoration:underline; font-size:12px; } #yop-poll-vote-31_yp58cf5c30bed76 div { float:left; width:100%; } /* End Vote Button*/ /* Start Messages*/ #yop-poll-container-error-31_yp58cf5c30bed76 { font-size:12px; font-style:italic; color:red; text-transform:lowercase; margin-bottom:20px; text-align:center; } #yop-poll-container-success-31_yp58cf5c30bed76 { font-size:12px; font-style:italic; color:green; margin-bottom:20px; text-align:center; } /* End Messages*/#yop-poll-container-31_yp58cf5c30bed76 img { max-width: 1000; } .yop-poll-forms-display{}
How much of your code is covered by Unit Tests?
  • What unit test? Oh, um, zero.
  • Those old things? Its probably like 25% or less.
  • We try but we're somewhere between 25 to 50% depending on the project.
  • We're on top of things. Our tests cover 75% of our code.
  • We're amazing. Our code is covered 100% by unit tests. And sprinkled with the glittery dust of a unicorn's breathe.
  • Wait, work? Or personal? Work, um not so much. Personal, you'd be proud.
Clean Code

Seriously, read this book!

Podcast News

iTunes: AUS Dan G, bryangrove, Criviere, Kasprs, sulhogar, Niil Ohlin (Neil Ilin)
Stitcher Reviews: indiegamer21, makeACaseForCamelCase, athyng, brokenrelay, El_Zilcho

MongoDb and ElasticSearch Ransomware Attacks
http://www.pcworld.com/article/3157417/security/after-mongodb-ransomware-groups-hit-exposed-elasticsearch-clusters.html

Alexa 7 Minute Workout
https://www.amazon.com/Pargee-7-Minute-Workout/dp/B018WUNBE6

Question: Does every programmer spend their nights coding?!

Send us a SASE – http://www.codingblocks.net/swag

Winner of Clean Code for Episode 52
Kevin Kemier – @kevinkemler

Thanks for the post cards from Wroclaw and Gdansk, Poland Rocks!
Community Spotlight: http://www.codingblocks.net/community-spotlight/

Advice for new programmers? Make something fun and launch!
Mini Code Adventures:

  • Yeoman
  • Markov Chains

Unit Tests

Three laws of TDD

  1. You may not write production code until you have written a failing unit test
  2. You may not write more of a unit test than is sufficient to fail, and compiling is failing
  3. You may not write more production code than is sufficient to pass the currently failing test

Keeping Tests Clean

Problem with this approach – test code could outgrow your prod code and become unmanageable
Is dirty test code better than no test code?

  • Tests must change as the production code changes
  • The dirtier the tests, the harder they are to change
  • Tests can become a liability due to technical debt of the dirtiness

Abandoning test code has the following consequences

  • Production code defects rise
  • Fear of changing code increases
  • Cleaning / refactoring code descreases due to lack of confidence (Code rot!!!)

Test code is as important as production code – it should be treated as a first class citizen and should be as clean as production code.

Tests Enable the -ilities

  • Tests are what keep your production code flexible, maintainable and reusable.
  • Tests allow you to make changes to code without fear.
  • Tests enable change.
  • Tests enable improving architecture.

Without tests, your code base rots.

Clean Tests

  • Readability
  • More important in Unit Tests than in production code?
  • Clarity
  • Simplicity
  • Density of expression

Much like writing great functions, if you have to learn a ton of details to make heads or tails of a test, it can be improved.

Build – Operate – Check Pattern

Build – builds up the test data
Operate – works on the test data
Check – ensure the operation yielded the expected results

Great example in the book of refactoring an ugly test to a clean one

Domain Specific Testing Language

  • Tests are written in specific ways for various testing platforms
  • Helps readability

Double Standard?

Interesting points made on asserts in line with values…
Author chose to do upper / lower combination of characters in an initialism to indicate whether the particular test result should have been true or false

Unit tests are often not held to the same standard in terms of performance

  • StringBuilder in production
  • String Concatenation in tests

One assert per test

  • Makes tests very easy to read
  • Given, When, Then naming
    Author actually prefers multiple asserts in some scenarios (XML example from book)
    Author notes that single assert is a good guideline
    Should try to minimize the number of asserts

Single concept per test

More important than a single assert per test
Ensures that your tests are laser focused and not testing miscellaenous (non-related) things

FIRST

  • (F)ast – tests should be fast / run quickly
  • (I)ndependent – tests should NOT depend on each other – tests should be able to be run in any order they like
  • ®epeatable – they should be repeatable in ANY environment without need for any specific infrastructure
  • (S)elf-validating – they should have a boolean output – pass or fail, nothing else
  • (T)imely – they need to be written in a timely fashion – just before the production code is written – ensures they are easy to code against

Importance

Unit Tests are as important if not moreso than the production code they’re for becasue they allow you to make changes confidently and without fear. They allow you to mold your code over time to improve flexibility / maintainability.

Resources we Like

Tips of the Week

  • Joe: Glyphfriend from Rion (intellisense previews of icons) and https://github.com/workshopper/learnyounode”>Learn You Node from ju66ernaut
  • Allen: Visual Studio – Increase / Decrease Font Size with
    ctrl + shift > <
  • Michael: Structuring unit tests. A combination of Roy Osherove’s and Phil Haack’s recommendation
    [TestFixture]
    public class CustomerTests
    {
    	[TestFixture]
    	public class GetFullName
    	{
    		[Test]
    		public void GetFullName_WhenMiddleNameIsBlank_ReturnsNameAsFirstSpaceLast() 
    		{
    			// Arrange 
    			...
    
    			// Act 
    			...
    
    			// Assert
    			...
    		}
    	}
    
    	[TestFixture]
    	public class GetLastName 
    	{
    		[TestCase("Outlaw", "Outlaw")]
    		[TestCase("Underwood", "Underwood")]
    		[TestCase("Zack", "Zack")]
    		public void GetLastName_WhenLastNameHasBeenSet_ReturnsTheLastName(string testcase, string expect)
    		{
    			// Arrange
    			var customer = new Customer 
    			{
    				lastname = testcase
    			};
    
    			// Act
    			var result = customer.GetLastName();
    
    			// Assert
    			Assert.AreEqual(expect, result);
    		} 
    	}
    }

Show summary

Chapter 9 – Clean Code’s Unit Tests
Unit test code is as important as production code because they allow you to make changes confidently and correctly, improving your flexibility and maintainability over time

Episode source