A Basic Introduction of how to write Unit Test for beginners.

Introduction

In this article you will have basic introduction of Unit Test and will learn how to write Unit Test in C#.  Writing test case is an inevitable part of software testing. Testing software is a real challenge, because there are so many types of test cases that come in so many different shapes and sizes. In order to learn how to write good Unit Test, we must first understand as to what is Unit Test and why do we need it. So lets learn that first

What do you mean by a Unit Test ?

Unit Tests simply verifies that individual units of code (mostly functions) work as expected. Usually you write the test cases yourself, but some can be automatically generated. Performing unit tests is designed to be simple, generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function. The objective in unit testing is to isolate a unit and validate its correctness. A manual approach to unit testing may employ a step-by-step instructional document.

Why do we need Unit Test ?

One of the most valuable benefits of Unit Tests is that they give you confidence that your code works as you expect it to work. Unit Tests give you the confidence to do long-term development because with unit tests in place, you know that your foundation code is dependable. Unit Tests give you the confidence to refactor your code to make it cleaner and more efficient.

There are few reasons that make you understand why a developer need to design and write out test cases to make sure major requirements of a module being validated during testing:

  • Unit testing increases confidence in changing/ maintaining code. If good unit tests are written and if they are run every time any code is changed, we will be able to promptly catch any defects introduced due to the change.
  • Unit testing finds problems early in the development cycle. This includes both bugs in the programmer’s implementation and flaws or missing parts of the specification for the unit.
  • Codes are more reusable. In order to make unit testing possible, codes need to be modular. This means that codes are easier to reuse.
  • Unit testing may reduce uncertainty in the units themselves and can be used in a bottom-up testing style approach.
  • Development is faster.
  • Codes are more reliable.
  • Easy to automate.

Lets start the show – Create your First Unit Test(Step by Step)

In this article, I would like to show that unit tests are quite easy.  Unit testing is a way for the programmer to make sure that the code that is written is fully functional and works the way it is supposed to work. Unlike the standard testing method, when a piece of code is ran an the developer or tester manually feeds the values, unit tests can test specific methods/functions (or any other code elements) by providing the test data in code.

One of the fundamental principles of unit testing is to follow TDD(Test Driven Development) where we have to write tests first, and then write the simplest code that will make the test pass. Here I am going to follow just opposite approach to make you learn how to write and Test code first. Later we will discuss TDD concept. In this article we are going to follow different approach where we will write simple code first, and then create the Unit Tests based on the possible situations. As discussed earlier, we can also write Tests first, and then write the code that will make the test pass. It depends upon individuals which one of the way to follow to test code.

Here I’ve written a basic program which can be easily understandable by any novice who’ve just started to learn C# and want to learn how to write unit test.

 public class BasicMaths
 {
 public double Add(double num1, double num2)
 {
 return num1 + num2;
 }
 public double Substract(double num1, double num2)
 {
 return num1 - num2;
 }
 public double divide(double num1, double num2)
 {
 return num1 / num2;
 }
 public double Multiply(double num1, double num2)
 {
 // To trace error while testing, writing + operator instead of * operator.
 return num1 + num2;
 }
 }

In this program, you can see that there are four basic math function Add, Substract, Divide and Multiply. All function having two double datatype parameter.

MS Unit Tests

To test above four methods, we are going to use Microsoft Testing Tools which is  MS Unit Test. To add MS unit Test follow the steps given in below image.

MSUnitTest_2

First move to Solution Explorer ( shortcut Ctrl + Alt + L to open Solution Explorer).

  • Right Click on Solution ‘Project Name’
  • Click on Add
  • Click on New Project

It will open a ‘Add New Project‘ window. Follow the given steps to create and add Unit Test Project.

MSUnitTest_3

  • Click on Test
  • Select Unit Test Project from list of available templates.
  • Write name of project. Here we are using BasicMathTest and then Click on Ok button.

It created BasicMathTest project along with BasicMath Project whose functions need to be tested. To access all four method of BasicMath in test project we need to add it reference in test project. Take a look in below image to know how to add.

MSUnitTest_4

  • Right click on Reference of MS Unit Test Project
  • Click on Add Reference

It will open a Reference Manager window. To add reference, click on Projects – Solutions – BasicMaths and click on Ok button.

You can see in below image that the reference has been added .

  • BasicMath – Having all functions which need to be tested
  • Microsoft.VisualStudio.QualityTools.UnitTestFramework – It contains all classes and methods that provide unit testing support.

MSUnitTest_10

Great, you should have something like this

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace BasicMathTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// TODO : Write test code
}
}
}

What will we do next is add our code to test functions of BasicMath Project.

First add namespaces

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BasicMath;

The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.

The Microsoft.VisualStudio.TestTools.UnitTesting namespace supplies classes that provide unit testing support. This namespace contains many attributes that identify test information to the test engine regarding data sources, order of method execution, program management, agent/host information, and deployment data. The Microsoft.VisualStudio.TestTools.UnitTesting namespace also contains custom unit testing exceptions.

The BasicMath namespace contains all functions which need to be tested like Add, Substract, Multiply and Divide

Some Requirements that need to be followed

Test class requirements :

The minimum requirements for a test class are the following:

  • The [TestClass] attribute is required in the Microsoft unit testing framework for managed code for any class that contains unit test methods that you want to run in Test Explorer.
  • Each test method that you want Test Explorer to run must have the [TestMethod]attribute.

Test method requirements :

A test method must meet the following requirements:

  • The method must be decorated with the [TestMethod] attribute.
  • The method must return void.
  • The method cannot have parameters.

Writing first Unit Test method

Here, we will write Unit Test methods to verify the behavior of the Add method of the BasicMaths class. Code will look like as given below

MSUnitTest_6

In same way write test code for all method like Substract, Multiply and Divide. After adding all required test method, Our test code will look like as given below :

[TestClass]
public class UnitTest1
{

[TestMethod]
public void Test_AddMethod()
{
BasicMaths bm = new BasicMaths();
double res = bm.Add(10, 10);
Assert.AreEqual(res, 20);
}

[TestMethod]
public void Test_SubstractMethod()
{
BasicMaths bm = new BasicMaths();
double res = bm.Substract(10, 10);
Assert.AreEqual(res, 0);
}

[TestMethod]
public void Test_DivideMethod()
{
BasicMaths bm = new BasicMaths();
double res = bm.divide(10, 5);
Assert.AreEqual(res, 2);
}

[TestMethod]
public void Test_MultiplyMethod()
{
BasicMaths bm = new BasicMaths();
double res = bm.Multiply(10, 10);
Assert.AreEqual(res, 100);
}
}

We can see that in every test function We use the Microsoft unit test framework for managed code Assert.AreEqual method to verify that the ending balance is what we expect.

Build and run the test

To build and run the test.

  • Either go to Solution Explorer (Ctrl +Alt+L) and right click on Solution ‘BasicMath’ and Click on Build Solution or go to Build Menu (Alt + B) and Click on Build Solution.
  • Choose Test Menu  -> Run -> All Test. Or instead of this step you can follow given step also
  • Go to Test Explorer and Click on Run All to run tests for all test methods .

MSUnitTest_7

As the test is running the status bar at the top of the window is animated. At the end of the test run, the bar turns green if all the test methods pass, or red if any of the tests fail.
You should now see something like this :

MSUnitTest_9

In this case, If the test does fail. The test method is moved to the Failed Tests. group. Select the method in Test Explorer to view the details at the bottom of the window.

Fix your code and rerun your tests 

Analyze the test results –  The test result contains a message that describes the failure. For the AreEquals method, message displays you what was expected (the (Expected<XXX>parameter) and what was actually received (the Actual<YYY> parameter).  In this case, Message was Assert.AreEqual failed. Expected:,Actual

Correct the bug  – To correct the error, simply replace + with *.


public double Multiply(double num1, double num2)
{
return num1 * num2;
}

Rerun the Test – In Test Explorer, choose Run All to rerun the test. The red/green bar turns green, and the test is moved to the Passed Tests group.

MSUnitTest_12

Cheers! We learned how to write Unit Test.

MSUnitTestPassed1

TDD(Test Driven Development) Implementation using Unit Testing in C#

As we discussed earlier in this article that most of the developer follow write Test first then Code Later approach, we are going to learn TDD approach and how to use it.

Test-driven development (TDD) is primarily a specification technique with a side effect of ensuring that your source code is thoroughly tested at a confirmatory level.  TDD is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards.

MSunitesttdd1

A significant advantage of Test-driven development (TDD) is that it enables you to take small steps when writing software. As for example, Let us assume you add some new functional code, compile, and test it.  Chances are pretty good that your tests will be broken by defects that exist in the new code. It is much easier to find, and then fix, those defects if you’ve written two new lines of code than two thousand. The implication is that the faster your compiler and regression test suite, the more attractive it is to proceed in smaller and smaller steps. It is generally prefer to add a few new lines of functional code before recompile and rerun tests.

Msunittesttdd2

The motto of test-driven development is “Red, Green, Refactor.”

  • Red: Create a test and make it fail.
  • Green: Make the test pass by any means necessary.
  • Refactor: Change the code to remove duplication in your project and to improve the design while ensuring that all tests still pass.

The Red/Green/Refactor cycle is repeated very quickly for each new unit of code.

Let’s Implement TDD using MS Unit Testing

Let’s take exact same sample of code which we’ve used earlier in this article. We will create four basic function like Add, Substract, Multiply and Divide which will need to be tested. In earlier example we’ve written code first then Unit Test later but as this is TDD implementation we will write Unit Test first then will write code later.

To Write Unit Test. Follow the steps given in below image.

  • Create new project. Click on Test.
  • Click on Unit Test Project
  • Write Project name. Eg – BasicMathTDDTest and then Click on Ok button

MsUnitTest_13

you will get default code template as given below to write your test code.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace BasicMathTDDTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void Test_Method1()
{
// TODO : Add test logic here
}
}
}

Here we are going to write test code first before writing actual code which need to be tested.

MsUnitTest_14

Code will look like as given below


  public class UnitTest1
    {
        [TestMethod]
        public void Test_AddMethod()
        {
            BasicMaths bm = new BasicMaths();
            double res = bm.Add(20.50, 20.50);
            Assert.AreEqual(41, res);
        }

        [TestMethod]
        public void Test_MultiplyMethod()
        {
            BasicMaths bm = new BasicMaths();
            double res = bm.Multiply(10, 10);
            Assert.AreEqual(100, res);
        }
    }

As you can see that there are two test method Test_AddMethod and Test_MultiplyMethod and both method is using BasicMaths class, Add and Multiply method which is not yet defined. When we run this application you will get error as given below :

MsUnitTest_15

To make MS Unit Test run, we need to create BasicMaths class and add reference to Unit Test project. Follow given steps to know how to create BasicMaths class and adding reference to MS Unit Test Project.

  • Right click on Solution ‘BasicMathTDDTest’
  • Click on ADD
  • Click on New Project

MsunitTest_16

It will open a Add New Project window where you have to follow given steps

  • Click on Visual C# ( If you are writing code in C# language )
  • Click on Console Application
  • Write Name of Project, Here Project Name is BasicMath  and click on OK button

MsUnitTest_17

Now write Add and Multiply Method under BasicMaths class for which we have already written MS Unit Test. Code will look like as given below


public class BasicMaths
{
public double Add(double num1, double num2)
{
return num1 + num2;
}

public double Multiply(double num1, double num2)
{
return num1 + num2;
}

MsUnitTest_18

After writing code you can see that there is 0 references of BasicMaths class as well as Add method function but these function is already being used in MS Unit Test project. To make it accessible we need to add this project to MS Unit Test Project reference.

Once you add reference, Its time to run Test. To run Test you can either go to Test -> Run -> All Test or move to Test Explorer and click on Run All.  After running Tests you will see output as given below

MsUnitTest_19

Both Test Method Test_AddMethod and Test_MultiplyMethod is failed. To Know why These method failed while Testing click on each Method and read the reason.

In Test_AddMethod Assert.AreEqual  is supposed to give 41 as actual value but we are expecting 21. It must be 41 to get Test passed. Ofcourse after adding 20.50 and 20.50 we will get 41. So We have written wrong expected value. Change it to 41 instead of 21.

MsUnitTest_20

In Test_MultiplyMethod Assert.AreEqual is supposed to give 20 but we are expecting 100. It must be 20 to get test passed. But Logically after multiplying 10 and 10 we should get 100 then why its actual value is returning 20. Check code of Multiply Method in BasicMaths class.

MsUniTest_21

As we can see that we are using +(Plus) operator between two operand num1 and num2 which should be *(Multiply) operator. Now given code is logically correct one.

  public double Multiply(double num1, double num2)
        {
            return num1 * num2;
        }

MsUnitTest_22

After correcting wrongs values and codes. Lets run Test again and see the result. Both Test method Test_AddMethod and Test_MultiplyMethod is passed.

Download Source Code :  Click Me to Download

Last Words 

I hope this article will help you to learn basics of Unit Test and how to create Unit Test cases for your code in C#.  Your all suggestions are most welcome and appreciated.

Advertisements
Posted in .Net, C#, Uncategorized | Tagged , , | Leave a comment

“Compare World Time” – A free app for Windows Phone Users to find and compare date and time of different countries and places

Here come my one more windows phone application in the windows phone store. This application is free for all windows phone users. With the help of this application, someone can easily find the exact time of any places and moreover they can compare time between different places. Its works simply as World Time Converter.

About App –
A simple yet elegant World Time application with almost all countries and their capital to add. Compare World Time app help you to view times of different places around the globe.It provides a list of predefined zones from which you can select and you can also add custom defined zones.
Features –
* One screen application. Add and delete from the same screen.
* Search for a city or country
* Long Press on a row to Delete

Download App –
Get free Compare World Time App -[Download]

Note – I am going to implement some more and Interesting features in this app. If you have any suggestions or feedback. please ping me. I’ll happy to listen your Ideas.

Screenshot –

I hope you liked this app. 🙂

Posted in General, Windows Phone, Windows Phone App | Tagged , , | 1 Comment

How to solve “Not enough memory” error and Windows Phone 8 Emulator does not start in Windows 8.1

If you are a Windows Phone developer and have upgraded your system from windows 8 to windows 8.1 then you might have faced “Not enough memory” error problem. If you are facing same problem then stop worrying, Microsoft exposed the symptom, reasons and solution of “Not enough memory” error message and Windows Phone 8 Emulator does not start in Windows 8.1
Here is the link – http://support.microsoft.com/kb/2911380

Reason –

If you are a windows 8.1 user and your system having less than 8 GB ram and moreover you are simultaneously running many programs with developing apps for windows phone, then it is quite obvious that Windows Phone 8 emulator won’t start and will throw a message as given below :

The Windows Phone Emulator wasn’t able to ensure the virtual machine was running: Something happened while starting a virtual machine: ‘Emulator Name’ could not initialize. (Virtual machine ID GUID) Not enough memory in the system to start the virtual machine Emulator Name with ram size 1024 megabytes. (Virtual machine ID GUID)”

rrk-wpmemoryerror

Ok fine, but a question can stuck in your mind that,
How same program used to run in windows 8 platform but it fails on windows 8.1 ?
Microsoft stated that this problem occurs in Windows 8.1 because the operating system is more conservative than the Windows 8 version about how it allocates memory to maintain consistently high performance. In Windows 8.1, Hyper-V memory management accounts for the memory that is consumed by programs before it starts any emulator instances. Hyper-V did not make this consideration in Windows 8.

Solution –

If the emulator still does not start, you can disable the Hyper-V runtime memory monitoring functionality by adding a MemoryReserve registry.

To do this, follow these steps:

Step 1) Start Registry Editor.
Step 2) Locate the following registry subkey: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization
Step 3) Right-click the Virtualization folder, point to New, and then click DWORD Value.
Step 4) Type MemoryReserve, and then press Enter.
Step 5) Double-click MemoryReserve,
Step 6) Under Value data field, type 2048
Step 7) Select Decimal option and click OK
Step 8) Close Registry Editor
Step 9) Restart your system.

Note : Before you modify anything in registry file, make sure that you made the back up the registry for restoration in case any problems occur.

Posted in CodeProject, Tips&Tricks, Windows 8, Windows Phone | Tagged , , | Leave a comment

How to Save Image in Local Photos album of Windows Phone ?

Sometimes you may want to develop a windows phone app which containing many images to view like WallPaper app for Windows Phone LockScreen, Celebrity album, etc . It is quite easy to display images by using Image Control and passing source path to respective Image Control, but is it enough to just give functionality to see images only ? User always like to keep good images in their phone. so, In that condition user should have an app that can provide facility of save images also. This blog simply shows how you can write code that would allow user to save Image locally in their Save Image Photo album.

Implementation –

Here, you can see some piece of code which containing a function SaveImageToPhotoHub with few statements and a parameter type WriteableBitmap. This SaveImageToPhotoHub function returns either true or false output. To work with this function you just need to pass needed Image as parameter in SaveImageToPhotoHub function.

 private bool SaveImageToPhotoHub(WriteableBitmap bmp)
        {

            using (var mediaLibrary = new MediaLibrary())
            {
                using (var stream = new MemoryStream())
                {
                    var fileName = string.Format("Gs{0}.jpg", Guid.NewGuid());
                    bmp.SaveJpeg(stream, bmp.PixelWidth, bmp.PixelHeight, 0, 100);
                    stream.Seek(0, SeekOrigin.Begin);
                    var picture = mediaLibrary.SavePicture(fileName, stream);
                    if (picture.Name.Contains(fileName)) return true;
                }
            }
            return false;
        }

WriteableBitmap provides a BitmapSource that can be written to and updated. To declare WritableBitmap class you must include System.Windows.Media.Imaging namespace

using System.Windows.Media.Imaging;

MediaLibrary is a class which is used to access songs, playlists, and pictures in the device’s media library. To acess MediaLibrary class you need to include Microsoft.Xna.Framework.Media namespace

using Microsoft.Xna.Framework.Media;

SaveJpeg is an Extentions method which is responsible to encodes a WriteableBitmap object into a JPEG stream, with parameters for setting the target width and height of the JPEG file.

SavePicture is a method of MediaLibrary class which saves the image contained in the stream object to the media library, and then returns that saved image as a picture object.

To acess MemoryStream class you need to include System.IO namespace.

using System.IO;

Now take a look how to use the above method for saving image.

private void Save_Click(object sender, EventArgs e)
        {
            WriteableBitmap bmp = new WriteableBitmap(imgview, null);
            if (SaveImageToPhotoHub(bmp))
            {
                MessageBox.Show("Image Saved", "Information", MessageBoxButton.OK);
            }
            else
            {
                MessageBox.Show("Error : Image Not Saved", "Information", MessageBoxButton.OK);
            }
        }

Here, imgView is an Image Control which is placed in xaml part


Note :- To run this code properly your app should have capabilities to access Windows Phone windows phone media library hub. You can simply do this by checking ID_CAP_MEDIALIB_PHOTO from capabilities tab of WMAppManifest.xml

Isn’t it so easy to learn how to save image locally on Windows Phone device. I hope you liked this article and this will help you while writing code for your app.

Posted in C#, CodeProject, Tips&Tricks, Windows Phone, Windows Phone App | Tagged , , , , | 2 Comments

How to Solve issues of Internet not working with Windows Phone 8 emulator.

If you are facing issues while connecting Internet with Windows Phone 8 emulator during deployment process and getting error message like “Windows Phone emulator was not able to connect to Windows Phone operating system. Phone didn’t respond to connect request” or on opening IE(Internet Explorer) of Windows Phone emulator, getting message “We can’t connect to search right now. Make sure airplane mode is turned off, or check your cellular data or Wi-Fi connection” even you system is connected with Internet connection. However when you deploy same Windows Phone application of Windows Phone device(developer unlocked), it works fine without any issues. I can understand this one is weird to consider that same application is behaving differently with same wi-fi connection. I experienced same feeling after upgrading from Visual Studio 2012 to Visual Studio 2013 IDE with Windows 8 OS to Windows 8.1 OS though it was working fine on Windows 8 With Visual Studio 2012. I have tried many tips & tricks available on many websites, blogs and even on MSDN website-[Troubleshooting the Windows Phone 8 Emulator] but I was unable to solve the issues. Finally after using some more steps I am able to connect Internet with Windows phone 8 emulator using WI-FI.

Possible Solution to solve Internet Issues with Windows Phone 8 emulator : 

Follow given steps –

Step 1- Move to “Control Panel\All Control Panel Items\Administrative Tools”, Here remove each and every Virtual Machines listen under.
Step 2 – Remove Hyper-V and then Restart the System.
Step 3 – After restarting, Install Hyper-V once again.
Step 4 – Open Visual Studio and Run any Windows Phone 8 app to start the emulator.
Step 5 – It will create again all needed Virtual Machines( you can notice from Hyper-V Manager tools)
Step 6 – While loading emulator, it will prompt for letting the emulator access the internet. say yes.
Step 7 – Let the emulator and your project fully load
Step 8 – Now you need to shutdown the emulator( by closing directly or use Shift + F5) and close the Visual Studio.
Step 9 – Now Open Network and Sharing Centre
Step 10 – Click change Adapter Settings (Listed on the left hand side)
Step 11 – Now you will see there – “Control Panel\Network and Internet\Network” Connections. some new adapter created by HyperV, they should be called “vEthernet(…)”
Step 12 – Here, You need to focus on the vEthernet( Virtual Switch) and vEthernet (Internal Ethernet Port Windows Phone Emulator Internal Switch)
Step 13 – Now right click on vEthernet( Virtual Switch) and click on the properties and navigate to the sharing tab.
Step 14 – Here, Choose Allow other Network users to connect and choose the vEthernet (Internal Ethernet Port Windows Phone Emulator Internal Switch) as the adapter and then save the changes and close Windows.
Step 15-  Now open the properties on vEthernet (Internal Ethernet Port Windows Phone Emulator Internal Switch)
Step 16 – Here, You need to disable Internet Protocol Version 6 and double click on Internet Protocol Version 4
Step 17 – Now, Use the following IP address: 169.254.169.177 Subnet mask:255.255.0.0
Step 18 – After entering IP address and Subnet mask. You need to click on advanced button, under the IP settings tab, and then assign an interface metric: 1
Step 19 – Now Open your Visual Studio and run the Windows Phone 8 project.
Step 20 – Open Internet by using Search button or Internet Explorer of emulator and check Internet access.(Make sure your Wi-fi is working properly)

In my case, It works fine and I’ve shared this tips among some guys and they all solved the issues of Internet with Windows Phone 8 emulator. Hope this might help you also.

Posted in CodeProject, Tips&Tricks, Windows Phone | Tagged , | Leave a comment