Blog Post

My Second Pester Test

,

I should write about my first one, but I just copied Rob’s test, so that’s not so exciting. Instead, I decided to take his advice and write some code, then decide how I test it. This isn’t really TDD, but I need to understand how Posh returns things, so I’ll figure that out first.

I decided to work with SQL Clone, since that’s an area I’m working in a bit already. SQL Clone has a set of PoSh cmdlets that you can use to create database clones, so I thought that would be a good test.

What do I test?

My process is to remove a clone if it exists and then add one back. For testing, I need to consider what actually is happening here.

  • If a cloned database exists, remove it
  • Create a new cloned database

The result of this process means that I’ll have a Clone, no matter whether I created a new one or had to remove one and recreate a new one. Or, if I had a Clone already and my script failed. This last one is something a tester needs to be aware of.

In my case, I can determine if there is a new clone by looking at the created date of the database object. If that was later than the beginning of my test, then I could likely assume my clone was new.

To start with, I created a function that would destroy and create a simple clone. Once I had that, I could now write my Pester test.

I started with a “describe” element, in which I loaded my function and set a starting time.

Then in the “it” section, I run my function and then check the instance, getting the CreateDate property of my clone database. If my function has worked, this will be a new clone, created since my test started. I compare that to complete the test.

I ran this with Invoke-Pester, and it worked.

2017-11-28 14_58_31-powershell

This wasn’t simple. I had to test my test a few times, and use PoSh commands to verify it was doing what I thought. I also changed my function with a hardcoded db clone name to ensure the test fails. Results for that one here:

2017-11-28 14_59_55-powershell

Of course, I changed things back and tested again. Now, as I update my function to include adding in the instance name and image name,  this test should still pass. Of course, I can add in other tests, or change this one, to allow me to test on different images and instances as well.

A simple test, maybe a silly one, but I learned a few things about my PoSh code (and how to write it cleaner) as well as Pester and adding in another unit test framework. Now I can expand this to test other PoSh items I have and practice writing better tests that will give me confidence my code works in a variety of situations.

Filed under: Blog Tagged: powershell, SQL Clone, syndicated, testing

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating