<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Unit Testing &#8211; Sibeesh Passion</title>
	<atom:link href="https://mail.sibeeshpassion.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>https://mail.sibeeshpassion.com</link>
	<description>My passion towards life</description>
	<lastBuildDate>Wed, 02 Jun 2021 15:13:59 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>/wp-content/uploads/2017/04/Sibeesh_Passion_Logo_Small.png</url>
	<title>Unit Testing &#8211; Sibeesh Passion</title>
	<link>https://mail.sibeeshpassion.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>WCF Service Unit Tests Using NUnit With Rhino Mocks And Entity Framework</title>
		<link>https://mail.sibeeshpassion.com/wcf-service-unit-tests-using-nunit-with-rhino-mocks-and-entity-framework/</link>
					<comments>https://mail.sibeeshpassion.com/wcf-service-unit-tests-using-nunit-with-rhino-mocks-and-entity-framework/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Sun, 20 Nov 2016 13:58:15 +0000</pubDate>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[NUnit Tests]]></category>
		<category><![CDATA[NUnit With Rhino Mocks]]></category>
		<category><![CDATA[Rhino Mocks]]></category>
		<category><![CDATA[WCF]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11929</guid>

					<description><![CDATA[In this post we will see how we can write unit test cases for our WCF Service with a framework called NUnit. We will also be covering how to mock our dependencies in our test, here we wil be using Rhino Mocks. I am going to use Visual Studio 2015 for the development. I hope you will like this article. Download source code WCF_NUnit_Tests_Rhino_Mocks.zip Background As a developer, we all writes lots of codes in our day to day life. Am I right? It is more important to check whether the codes we have written works well. So for that [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In this post we will see how we can write unit test cases for our <a href="http://sibeeshpassion.com/category/WCF-Service/" target="_blank" rel="noopener">WCF Service</a> with a framework called NUnit. We will also be covering how to mock our dependencies in our test, here we wil be using Rhino Mocks. I am going to use <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015 for the development. I hope you will like this article. </p>
<p><strong>Download source code</strong></p>
<li>
<a href="https://code.msdn.microsoft.com/WCF-Service-Unit-Tests-f1fcedff" target="_blank" rel="noopener">WCF_NUnit_Tests_Rhino_Mocks.zip</a>
</li>
<p><strong>Background</strong></p>
<p>As a developer, we all writes lots of codes in our day to day life. Am I right? It is more important to check whether the codes we have written works well. So for that we developer usually do unit testing, few developers are doing a manual testing to just check whether the functionality is working or not. I would say that it is wrong. In a TDD (Test Driven Development) unit testing is very important, where we actually writes the test cases before we start our coding. Let us see what exactly the &#8220;Unit Tesing&#8221; is. </p>
<p><strong>Unit Testing</strong></p>
<p>Unit testing is the process of testing a unit, it can be a class, a block of codde, function, a property. We can easily test our units independently. In <a href="http://sibeeshpassion.com/category/asp-net/">dot net</a> we have so many frameworks to do unit testing. But here we are going to use NUnit which I found very easy to write tests. </p>
<blockquote><p>If you have Resharper installed in your machine, it will be more easier to execute and debug your tests. Here I am using Resharper in my Visual Studio, so the screenshots will be based on that. Thank you</p></blockquote>
<p>Now it is time to set up our project and start our coding.</p>
<p><strong>Setting up the project</strong></p>
<p>To get started, please create an empty project in your Visual Studio. </p>
<div id="attachment_11904" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png"><img fetchpriority="high" decoding="async" aria-describedby="caption-attachment-11904" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png" alt="empty_project" width="650" height="507" class="size-full wp-image-11904" srcset="/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png 458w, /wp-content/uploads/2016/10/Empty_Project-e1475921231766-300x234.png 300w, /wp-content/uploads/2016/10/Empty_Project-e1475921231766-400x312.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11904" class="wp-caption-text">empty_project</p></div>
<p>Now, we will add a <a href="http://sibeeshpassion.com/category/WCF-Service/" target="_blank" rel="noopener">WCF Service</a> as follows. </p>
<div id="attachment_11930" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Create_a_wcf_service.png"><img decoding="async" aria-describedby="caption-attachment-11930" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Create_a_wcf_service-1024x709.png" alt="create_a_wcf_service" width="634" height="439" class="size-large wp-image-11930" srcset="/wp-content/uploads/2016/11/Create_a_wcf_service-1024x709.png 1024w, /wp-content/uploads/2016/11/Create_a_wcf_service-300x208.png 300w, /wp-content/uploads/2016/11/Create_a_wcf_service-768x532.png 768w, /wp-content/uploads/2016/11/Create_a_wcf_service-160x110.png 160w, /wp-content/uploads/2016/11/Create_a_wcf_service-400x277.png 400w, /wp-content/uploads/2016/11/Create_a_wcf_service-866x600.png 866w, /wp-content/uploads/2016/11/Create_a_wcf_service.png 1178w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11930" class="wp-caption-text">create_a_wcf_service</p></div>
<p>Once you are done, you can see two files, an Interface(IMyService) and a class (MyService) with .svc extension. If you are completely new to WCF service, I strongly recommend you to read some basics <a href="https://msdn.microsoft.com/en-us/library/bb386386.aspx" target="_blank" rel="noopener">here</a>.</p>
<p>Now, it is time to set up our database and insert some data. </p>
<p><strong>Creating database</strong></p>
<p>Here I am creating a database with name &#8220;TrialDB&#8221;, you can always create a DB by running the query given below. </p>
<p>[sql]<br />
USE [master]<br />
GO</p>
<p>/****** Object:  Database [TrialDB]    Script Date: 20-11-2016 03:54:53 PM ******/<br />
CREATE DATABASE [TrialDB]<br />
 CONTAINMENT = NONE<br />
 ON  PRIMARY<br />
( NAME = N&#8217;TrialDB&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB.mdf&#8217; , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )<br />
 LOG ON<br />
( NAME = N&#8217;TrialDB_log&#8217;, FILENAME = N&#8217;C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\TrialDB_log.ldf&#8217; , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET COMPATIBILITY_LEVEL = 130<br />
GO</p>
<p>IF (1 = FULLTEXTSERVICEPROPERTY(&#8216;IsFullTextInstalled&#8217;))<br />
begin<br />
EXEC [TrialDB].[dbo].[sp_fulltext_database] @action = &#8216;enable&#8217;<br />
end<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULL_DEFAULT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_NULLS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_PADDING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ANSI_WARNINGS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ARITHABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_CLOSE OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_SHRINK OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS ON<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_CLOSE_ON_COMMIT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CURSOR_DEFAULT  GLOBAL<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET CONCAT_NULL_YIELDS_NULL OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET NUMERIC_ROUNDABORT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUOTED_IDENTIFIER OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECURSIVE_TRIGGERS OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  DISABLE_BROKER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DATE_CORRELATION_OPTIMIZATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TRUSTWORTHY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET ALLOW_SNAPSHOT_ISOLATION OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PARAMETERIZATION SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET READ_COMMITTED_SNAPSHOT OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET HONOR_BROKER_PRIORITY OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET RECOVERY SIMPLE<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  MULTI_USER<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET PAGE_VERIFY CHECKSUM<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DB_CHAINING OFF<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET TARGET_RECOVERY_TIME = 60 SECONDS<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET DELAYED_DURABILITY = DISABLED<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET QUERY_STORE = OFF<br />
GO</p>
<p>USE [TrialDB]<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET MAXDOP = 0;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET MAXDOP = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET LEGACY_CARDINALITY_ESTIMATION = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET LEGACY_CARDINALITY_ESTIMATION = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET PARAMETER_SNIFFING = ON;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET PARAMETER_SNIFFING = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION SET QUERY_OPTIMIZER_HOTFIXES = OFF;<br />
GO</p>
<p>ALTER DATABASE SCOPED CONFIGURATION FOR SECONDARY SET QUERY_OPTIMIZER_HOTFIXES = PRIMARY;<br />
GO</p>
<p>ALTER DATABASE [TrialDB] SET  READ_WRITE<br />
GO<br />
[/sql]</p>
<p><strong>Create a table and insert data in database</strong></p>
<p>To create a table, you can run the query below.</p>
<p>[sql]<br />
USE [TrialDB]<br />
GO</p>
<p>/****** Object:  Table [dbo].[Course]    Script Date: 20-11-2016 03:57:30 PM ******/<br />
SET ANSI_NULLS ON<br />
GO</p>
<p>SET QUOTED_IDENTIFIER ON<br />
GO</p>
<p>CREATE TABLE [dbo].[Course](<br />
	[CourseID] [int] NOT NULL,<br />
	[CourseName] [nvarchar](50) NOT NULL,<br />
	[CourseDescription] [nvarchar](100) NULL,<br />
 CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED<br />
(<br />
	[CourseID] ASC<br />
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]<br />
) ON [PRIMARY]</p>
<p>GO<br />
[/sql]</p>
<p>Now we can insert few data to our newly created table. </p>
<p>[sql]<br />
USE [TrialDB]<br />
GO</p>
<p>INSERT INTO [dbo].[Course]<br />
           ([CourseID]<br />
           ,[CourseName]<br />
           ,[CourseDescription])<br />
     VALUES<br />
           (1<br />
           ,&#8217;C#&#8217;<br />
           ,&#8217;Learn C# in 7 days&#8217;)<br />
 INSERT INTO [dbo].[Course]<br />
           ([CourseID]<br />
           ,[CourseName]<br />
           ,[CourseDescription])<br />
     VALUES<br />
           (2<br />
           ,&#8217;Asp.Net&#8217;<br />
           ,&#8217;Learn Asp.Net in 7 days&#8217;)<br />
INSERT INTO [dbo].[Course]<br />
           ([CourseID]<br />
           ,[CourseName]<br />
           ,[CourseDescription])<br />
     VALUES<br />
           (3<br />
           ,&#8217;SQL&#8217;<br />
           ,&#8217;Learn SQL in 7 days&#8217;)<br />
INSERT INTO [dbo].[Course]<br />
           ([CourseID]<br />
           ,[CourseName]<br />
           ,[CourseDescription])<br />
     VALUES<br />
           (4<br />
           ,&#8217;JavaScript&#8217;<br />
           ,&#8217;Learn JavaScript in 7 days&#8217;)<br />
GO<br />
[/sql]</p>
<p>So our data is ready, that means we are all set to write our service and tests. Now go to your solution and create an entity data model. </p>
<div id="attachment_11931" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Entity_Framework-e1479637932362.png"><img decoding="async" aria-describedby="caption-attachment-11931" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Entity_Framework-e1479637932362.png" alt="entity_framework" width="634" height="686" class="size-full wp-image-11931" srcset="/wp-content/uploads/2016/11/Entity_Framework-e1479637932362.png 330w, /wp-content/uploads/2016/11/Entity_Framework-e1479637932362-277x300.png 277w, /wp-content/uploads/2016/11/Entity_Framework-e1479637932362-400x433.png 400w, /wp-content/uploads/2016/11/Entity_Framework-e1479637932362-555x600.png 555w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11931" class="wp-caption-text">entity_framework</p></div>
<p>So entity is also been created. Now please open your interface and that is where we start our coding. We can change the interface as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Runtime.Serialization;<br />
using System.ServiceModel;<br />
using System.Text;</p>
<p>namespace WCF_NUnit_Tests_Rheno_Mocks<br />
{<br />
    [ServiceContract]<br />
    public interface IMyService<br />
    {<br />
        [OperationContract]<br />
        Course GetCourseById(int courseId);<br />
        [OperationContract]<br />
        List&lt;Course&gt; GetAllCourses();<br />
    }<br />
}<br />
[/csharp]</p>
<p>Here we have created two operations, one to get a course by id and one to retrieve all the courses as a list. Now please go and implement these two operations in our service file. You can modify that class as follows. </p>
<p>[csharp]<br />
using System;<br />
using System.Collections.Generic;<br />
using System.Linq;<br />
using System.Runtime.Serialization;<br />
using System.ServiceModel;<br />
using System.Text;</p>
<p>namespace WCF_NUnit_Tests_Rheno_Mocks<br />
{<br />
    public class MyService : IMyService<br />
    {<br />
        private static MyEntity _myContext;<br />
        private static IMyService _myIService;</p>
<p>        public MyService()<br />
        {</p>
<p>        }</p>
<p>        public MyService(IMyService myIService)<br />
        {<br />
            _myContext = new MyEntity();<br />
            _myIService = myIService;<br />
        }<br />
        public Course GetCourseById(int courseId)<br />
        {<br />
            var crse = _myContext.Courses.FirstOrDefault(dt =&gt; dt.CourseID == courseId);<br />
            return crse;<br />
        }</p>
<p>        public List&lt;Course&gt; GetAllCourses()<br />
        {<br />
            var courses = (from dt in _myContext.Courses select dt).ToList();<br />
            return courses;<br />
        }<br />
    }<br />
}<br />
[/csharp]</p>
<p>In the above code, as you can see we are creating two constructor one is without parameter and other is with parameter, and we are having IMyService as a parameter. In this way we can achieve the dependency injection when we write tests for our unit. So what we need to do all is, just pass the dependency, in this case it is IMyService.</p>
<blockquote><p>In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. Source: WikiPedia</p></blockquote>
<p>If you need to know more on dependency injection, please read <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection" target="_blank" rel="noopener">here</a>. Now we will build and check whether our service is working fine or not. Please press CTRL+F5.</p>
<div id="attachment_11932" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Invoking_WCF_Service.png"><img decoding="async" aria-describedby="caption-attachment-11932" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Invoking_WCF_Service-e1479645357913.png" alt="invoking_wcf_service" width="634" height="403" class="size-full wp-image-11932" srcset="/wp-content/uploads/2016/11/Invoking_WCF_Service-e1479645357913.png 634w, /wp-content/uploads/2016/11/Invoking_WCF_Service-e1479645357913-300x191.png 300w, /wp-content/uploads/2016/11/Invoking_WCF_Service-e1479645357913-400x254.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11932" class="wp-caption-text">invoking_wcf_service</p></div>
<p>As our services are ready, we can now create the tests for those operations. For that we can create a new class library in our project and name it <em>UnitTest.Service</em>. Please add a class <em>MyServiceTests</em> in the class library where we can add our tests. And please do not forget to add our application reference too. </p>
<div id="attachment_11939" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Add_project_reference-e1479647898141.png"><img decoding="async" aria-describedby="caption-attachment-11939" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Add_project_reference-e1479647898141.png" alt="add_project_reference" width="634" height="438" class="size-full wp-image-11939" srcset="/wp-content/uploads/2016/11/Add_project_reference-e1479647898141.png 634w, /wp-content/uploads/2016/11/Add_project_reference-e1479647898141-300x207.png 300w, /wp-content/uploads/2016/11/Add_project_reference-e1479647898141-160x110.png 160w, /wp-content/uploads/2016/11/Add_project_reference-e1479647898141-400x276.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11939" class="wp-caption-text">add_project_reference</p></div>
<p><strong>Installing and configuring NUnit</strong></p>
<p>Now we can install NUnit to our test project from NuGet Package. Once you add the package, you will be able to add the preceding namespace in our <em>MyServiceTests</em> class.</p>
<p>[csharp]<br />
using NUnit.Framework;<br />
[/csharp]</p>
<p>In NUnit we have so many attributes that can be used for different purposes, but now we are going to use only four among them.</p>
<li>TestFixture</li>
<div id="attachment_11934" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966.png"><img decoding="async" aria-describedby="caption-attachment-11934" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966.png" alt="testfixture_in_nunit" width="634" height="191" class="size-full wp-image-11934" srcset="/wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966.png 634w, /wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966-300x90.png 300w, /wp-content/uploads/2016/11/TestFixture_In_NUnit-e1479646568966-400x121.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11934" class="wp-caption-text">testfixture_in_nunit</p></div>
<li>OneTimeSetUp</li>
<div id="attachment_11935" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit.png"><img decoding="async" aria-describedby="caption-attachment-11935" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-1024x283.png" alt="one_time_setup_attribute_in_nunit" width="634" height="175" class="size-large wp-image-11935" srcset="/wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-1024x283.png 1024w, /wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-300x83.png 300w, /wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-768x212.png 768w, /wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit-400x110.png 400w, /wp-content/uploads/2016/11/One_Time_SetUp_Attribute_In_NUnit.png 1337w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11935" class="wp-caption-text">one_time_setup_attribute_in_nunit</p></div>
<p>In previous versions, we were using <em>TestFixtureSetUp</em>, as the TestFixtureSetUp is obsolete, now we are using <em>OneTimeSetUp</em></p>
<div id="attachment_11937" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142.png"><img decoding="async" aria-describedby="caption-attachment-11937" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142.png" alt="testfixturesetup_attribute_is_obsolete" width="634" height="213" class="size-full wp-image-11937" srcset="/wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142.png 634w, /wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142-300x101.png 300w, /wp-content/uploads/2016/11/TestFixtureSetUp_attribute_is_obsolete-e1479646895142-400x134.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11937" class="wp-caption-text">testfixturesetup_attribute_is_obsolete</p></div>
<li>TearDown</li>
<p>This attribute is used to identify a method that is called immediately after each tests, it will be called even if there is any error, this is the place we can dispose our objects. </p>
<li>Test</li>
<p>This attribute is used to make a method callable from NUnit test runner. This can not be inherited. </p>
<p>Now we can see all these attributes in action. So let us write some tests, but the real problem is we need to mock the IMyService right as the parameterized constructor of the class <em>MyService </em> expecting it. Remember, we have discussed about setting up our services in the way which can be injected the dependencies? No worries, we can install Rhino Mock for that now. </p>
<div id="attachment_11938" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1.png"><img decoding="async" aria-describedby="caption-attachment-11938" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-1024x573.png" alt="rhino_mocks_in_nuget_package" width="634" height="355" class="size-large wp-image-11938" srcset="/wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-1024x573.png 1024w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-300x168.png 300w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-768x429.png 768w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-400x224.png 400w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1-1073x600.png 1073w, /wp-content/uploads/2016/11/Rhino_Mocks_In_Nuget_Package-1.png 1486w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11938" class="wp-caption-text">rhino_mocks_in_nuget_package</p></div>
<p>So we can add the tests are dependencies as follows in our test class.</p>
<p>[csharp]<br />
using NUnit.Framework;<br />
using Rhino.Mocks;<br />
using WCF_NUnit_Tests_Rhino_Mocks;</p>
<p>namespace UnitTest.Service<br />
{<br />
    [TestFixture]<br />
    public class MyServiceTests<br />
    {<br />
        private static MyService _myService;<br />
        private IMyService _myIservice;<br />
        [OneTimeSetUp]<br />
        public void SetUp()<br />
        {<br />
            _myIservice = MockRepository.GenerateMock&lt;IMyService&gt;();<br />
            _myService = new MyService(_myIservice);</p>
<p>        }</p>
<p>        [TearDown]<br />
        public void Clean()<br />
        {</p>
<p>        }</p>
<p>        [Test(Description = &quot;A test to check whether the returned value is null&quot;)]<br />
        public void GetCourseById_Return_NotNull_Pass()<br />
        {<br />
            //Set Up<br />
            var crs = new Course<br />
            {<br />
                CourseID = 1,<br />
                CourseName = &quot;C#&quot;,<br />
                CourseDescription = &quot;Learn course in 7 days&quot;<br />
            };<br />
            _myIservice.Stub(dt =&gt; dt.GetCourseById(1)).IgnoreArguments().Return(crs);</p>
<p>            //Act<br />
            crs = _myService.GetCourseById(1);</p>
<p>            //Assert<br />
            Assert.IsNotNull(crs,&quot;The returned value is null&quot;);<br />
        }</p>
<p>        [Test(Description = &quot;A test to check we get all the courses&quot;)]<br />
        public void GetAllCourses_Return_List_Count_Pass()<br />
        {<br />
            //Act<br />
            var crs = _myService.GetAllCourses();</p>
<p>            //Assert<br />
            Assert.AreEqual(4, crs.Count,&quot;The count of retrieved data doesn&#8217;t match&quot;);<br />
            _myIservice.VerifyAllExpectations();<br />
        }</p>
<p>    }<br />
}<br />
[/csharp]</p>
<p>As you can see we have mocked our IMyService as follows. </p>
<p>[csharp]<br />
_myIservice = MockRepository.GenerateMock&lt;IMyService&gt;();<br />
[/csharp]</p>
<div id="attachment_11940" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Generate_Mock_With_Rhino.png"><img decoding="async" aria-describedby="caption-attachment-11940" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Generate_Mock_With_Rhino-1024x247.png" alt="generate_mock_with_rhino" width="634" height="153" class="size-large wp-image-11940" srcset="/wp-content/uploads/2016/11/Generate_Mock_With_Rhino-1024x247.png 1024w, /wp-content/uploads/2016/11/Generate_Mock_With_Rhino-300x72.png 300w, /wp-content/uploads/2016/11/Generate_Mock_With_Rhino-768x185.png 768w, /wp-content/uploads/2016/11/Generate_Mock_With_Rhino-400x97.png 400w, /wp-content/uploads/2016/11/Generate_Mock_With_Rhino.png 1131w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11940" class="wp-caption-text">generate_mock_with_rhino</p></div>
<p>And, in the test <em>GetCourseById_Return_NotNull_Pass</em> we have also used a method called <em>Stub</em>. Stub actually tell the mock object to perform a certain action when a matching method is called, and it doesn&#8217;t create an expectation for the same. So you might be thinking, how can we create an expectation? For that we have a method called <em>Expect</em>.</p>
<div id="attachment_11941" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Expect_In_Rhino_Mock.png"><img decoding="async" aria-describedby="caption-attachment-11941" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Expect_In_Rhino_Mock-e1479648794975.png" alt="expect_in_rhino_mock" width="634" height="149" class="size-full wp-image-11941" srcset="/wp-content/uploads/2016/11/Expect_In_Rhino_Mock-e1479648794975.png 634w, /wp-content/uploads/2016/11/Expect_In_Rhino_Mock-e1479648794975-300x71.png 300w, /wp-content/uploads/2016/11/Expect_In_Rhino_Mock-e1479648794975-400x94.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11941" class="wp-caption-text">expect_in_rhino_mock</p></div>
<p>It is always recommended to verify your expectation when you use <em>Expect</em> as we used it in our test <em>GetAllCourses_Return_List_Count_Pass</em>.</p>
<p>[csharp]<br />
_myIservice.VerifyAllExpectations();<br />
[/csharp]</p>
<p>As I already said, I am using Resharper, we have so many shortcuts to run our tests, now if you right click on your <em>TestFixture</em>. You can see a run all option as preceding.</p>
<div id="attachment_11942" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532.png"><img decoding="async" aria-describedby="caption-attachment-11942" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532.png" alt="run_all_test_option_in_resharper" width="634" height="574" class="size-full wp-image-11942" srcset="/wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532.png 394w, /wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532-300x272.png 300w, /wp-content/uploads/2016/11/Run_all_test_option_in_Resharper-e1479649326532-400x362.png 400w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11942" class="wp-caption-text">run_all_test_option_in_resharper</p></div>
<blockquote><p>As I was getting an error as &#8220;No connection string named &#8216;Entity&#8217; could be found in the application config file.&#8221; when I run the tests, I was forced to install the entity framework in my test project and also add a new config file with the connection string like we have in our web config file. </p></blockquote>
<p>If everything goes fine and you don&#8217;t have any errors, I am sure you will get a screen as preceding. </p>
<div id="attachment_11943" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/11/NUnit_Output.png"><img decoding="async" aria-describedby="caption-attachment-11943" src="http://sibeeshpassion.com/wp-content/uploads/2016/11/NUnit_Output-1024x288.png" alt="nunit_output" width="634" height="178" class="size-large wp-image-11943" srcset="/wp-content/uploads/2016/11/NUnit_Output-1024x288.png 1024w, /wp-content/uploads/2016/11/NUnit_Output-300x84.png 300w, /wp-content/uploads/2016/11/NUnit_Output-768x216.png 768w, /wp-content/uploads/2016/11/NUnit_Output-400x112.png 400w, /wp-content/uploads/2016/11/NUnit_Output.png 1206w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11943" class="wp-caption-text">nunit_output</p></div>
<p>Happy coding!.</p>
<p><strong>See also</strong></p>
<li><a href="https://msdn.microsoft.com/en-us/library/ms182532.aspx" target="_blank" rel="noopener">Walkthrough: Creating and Running Unit Tests for Managed Code</a></li>
<li><a href="https://www.nunit.org/" target="_blank" rel="noopener">NUnit</a></li>
<li><a href="https://www.hibernatingrhinos.com/oss/rhino-mocks" target="_blank" rel="noopener">Rhino Mocks</a></li>
<p><strong>Conclusion</strong></p>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<p><strong>Your turn. What do you think?</strong></p>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/wcf-service-unit-tests-using-nunit-with-rhino-mocks-and-entity-framework/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Writing JavaScript Tests Using Jasmine Framework</title>
		<link>https://mail.sibeeshpassion.com/writing-javascript-tests-using-jasmine-framework/</link>
					<comments>https://mail.sibeeshpassion.com/writing-javascript-tests-using-jasmine-framework/#disqus_thread</comments>
		
		<dc:creator><![CDATA[SibeeshVenu]]></dc:creator>
		<pubDate>Mon, 10 Oct 2016 00:00:33 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Jasmine Framework]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Unit Testing With Jasmine]]></category>
		<guid isPermaLink="false">http://sibeecst_passion.com/?p=11903</guid>

					<description><![CDATA[[toc] Introduction In this post we will see how we can write unit test cases in JavaScript. Here we are going to use a framework called Jasmine to write and test our unit test cases. Jasmine is a behavior driven development framework to test our JavaScript codes. The interesting things about Jasmine framework are, it doesn&#8217;t even require a DOM, independent on any framework, clean and easy. Here I will show you how we can create and run our JavaScript tests. I am going to use Visual Studio 2015 for the development. I hope you will like this article. Download [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>[toc]</p>
<h2>Introduction</h2>
<p>In this post we will see how we can write unit test cases in <a href="http://sibeeshpassion.com/category/JavaScript/" target="_blank" rel="noopener">JavaScript</a>. Here we are going to use a framework called Jasmine to write and test our unit test cases. Jasmine is a behavior driven development framework to test our JavaScript codes. The interesting things about Jasmine framework are, it doesn&#8217;t even require a DOM, independent on any framework, clean and easy. Here I will show you how we can create and run our JavaScript tests. I am going to use <a href="http://sibeeshpassion.com/category/visual-studio/" target="_blank" rel="noopener">Visual Studio</a> 2015 for the development. I hope you will like this article.</p>
<h2><strong>Download source code</strong></h2>
<ul>
<li><a href="https://code.msdn.microsoft.com/Writing-JavaScript-Tests-2d1f99e9" target="_blank" rel="noopener">JavaScript Tests With Jasmine</a></li>
</ul>
<h2><strong>Background</strong></h2>
<p>As a developer, we all writes JavaScript codes for our client side developments. Am I right? It is more important to check whether the codes we have written works well. So for that we developer usually do unit testing, few developers are doing a manual testing to just check whether the functionality is working or not. But most of the MNC&#8217;s has set of rules to be followed while developing any functionalities, one of them is writing test cases, once the test cases passes, then only you will be allowed to move your codes to other environments. Here I will show you how we can write client side test cases with the help of a framework called Jasmine.</p>
<h2><strong>Setting up the project</strong></h2>
<p>To get started, please create an empty project in your Visual Studio.</p>
<div id="attachment_11904" style="width: 660px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png"><img decoding="async" aria-describedby="caption-attachment-11904" class="size-full wp-image-11904" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png" alt="empty_project" width="650" height="507" srcset="/wp-content/uploads/2016/10/Empty_Project-e1475921231766.png 458w, /wp-content/uploads/2016/10/Empty_Project-e1475921231766-300x234.png 300w, /wp-content/uploads/2016/10/Empty_Project-e1475921231766-400x312.png 400w" sizes="(max-width: 650px) 100vw, 650px" /></a><p id="caption-attachment-11904" class="wp-caption-text">empty_project</p></div>
<p>Now, we will install <a href="http://sibeeshpassion.com/category/jquery/" target="_blank" rel="noopener">jQuery</a>, <a href="http://sibeeshpassion.com/category/jquery-ui/" target="_blank" rel="noopener">jQueryUI </a>from Nuget package manager.</p>
<div id="attachment_11905" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Nuget_Package_Manager.png"><img decoding="async" aria-describedby="caption-attachment-11905" class="size-large wp-image-11905" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Nuget_Package_Manager-1024x478.png" alt="nuget_package_manager" width="634" height="296" srcset="/wp-content/uploads/2016/10/Nuget_Package_Manager-1024x478.png 1024w, /wp-content/uploads/2016/10/Nuget_Package_Manager-300x140.png 300w, /wp-content/uploads/2016/10/Nuget_Package_Manager-768x358.png 768w, /wp-content/uploads/2016/10/Nuget_Package_Manager-400x187.png 400w, /wp-content/uploads/2016/10/Nuget_Package_Manager-1287x600.png 1287w, /wp-content/uploads/2016/10/Nuget_Package_Manager.png 1842w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11905" class="wp-caption-text">nuget_package_manager</p></div>
<p>We are all set to start our coding now.</p>
<h3><strong>Creating page and needed JS file</strong></h3>
<p>Next, we are going to create a page as preceding, with two text boxes and needed references.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
&lt;title&gt;Writing JavaScript test cases with Jasmine framework &#8211; Sibeesh Passion&lt;/title&gt;<br />
&lt;meta charset=&#8221;utf-8&#8243; /&gt;<br />
&lt;link href=&#8221;Content/themes/base/jquery-ui.min.css&#8221; rel=&#8221;stylesheet&#8221; /&gt;<br />
&lt;link href=&#8221;Content/themes/base/base.css&#8221; rel=&#8221;stylesheet&#8221; /&gt;<br />
&lt;script src=&#8221;Scripts/jquery-3.1.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;Scripts/jquery-ui-1.12.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;Scripts/Index.js&#8221;&gt;&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
Start Date: &lt;input type=&#8221;text&#8221; name=&#8221;name&#8221; value=&#8221;&#8221; id=&#8221;dtStartDate&#8221; /&gt;<br />
End Date: &lt;input type=&#8221;text&#8221; name=&#8221;name&#8221; value=&#8221;&#8221; id=&#8221;dtEndDate&#8221; /&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<p>Now we can start writing our JavaScript codes in the file <em>Index.js</em>. We will start with a document ready function as preceding.</p>
<p>[js]<br />
$(function () {<br />
$(&#8220;#dtStartDate&#8221;).datepicker();<br />
$(&#8220;#dtEndDate&#8221;).datepicker();<br />
$(&#8220;#dtEndDate&#8221;).on(&#8220;change leave&#8221;, function () {<br />
});<br />
});<br />
[/js]</p>
<p>Shall we create our validation functions? We will be creating a namespace indexPage and functions. You can see the validations below.</p>
<p>[js]<br />
var indexPage = {};<br />
indexPage.validationFunctions = (function () {<br />
return {<br />
getStartDateSelectedValue: function () {<br />
return $(&#8220;#dtStartDate&#8221;).val();<br />
},<br />
getEndDateSelectedValue: function () {<br />
return $(&#8220;#dtEndDate&#8221;).val();<br />
},<br />
isNullValue: function (selVal) {<br />
if (selVal.trim() == &#8220;&#8221;) {<br />
return true;<br />
}<br />
else {<br />
return false;<br />
}<br />
},<br />
isNullValueWithUIElements: function () {<br />
if (indexPage.validationFunctions.isNullValue(indexPage.validationFunctions.getStartDateSelectedValue())<br />
&amp;&amp; indexPage.validationFunctions.isNullValue(indexPage.validationFunctions.getEndDateSelectedValue())) {<br />
alert(&#8220;The values can&#8217;t be null!.&#8221;);<br />
}<br />
},<br />
isEndDateGreaterStart: function () {<br />
var startDate = new Date(indexPage.validationFunctions.getStartDateSelectedValue());<br />
var endDate = new Date(indexPage.validationFunctions.getEndDateSelectedValue());<br />
if (startDate &lt; endDate) {<br />
return true;<br />
}<br />
else {<br />
alert(&#8220;End date must be greater than start date!.&#8221;)<br />
return false;<br />
}<br />
}<br />
}<br />
}(jQuery));<br />
[/js]</p>
<p>Hope you are able t understand the codes written. We are wrote some validations like Null value check, end date greater than start date etc&#8230;</p>
<p>Now please run your application and check whether the validations are working fine.</p>
<div id="attachment_11906" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Null_validation_check.png"><img decoding="async" aria-describedby="caption-attachment-11906" class="size-large wp-image-11906" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Null_validation_check-1024x319.png" alt="null_validation_check" width="634" height="198" srcset="/wp-content/uploads/2016/10/Null_validation_check-1024x319.png 1024w, /wp-content/uploads/2016/10/Null_validation_check-300x93.png 300w, /wp-content/uploads/2016/10/Null_validation_check-768x239.png 768w, /wp-content/uploads/2016/10/Null_validation_check-400x124.png 400w, /wp-content/uploads/2016/10/Null_validation_check.png 1231w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11906" class="wp-caption-text">null_validation_check</p></div>
<div id="attachment_11907" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Date_validation_check.png"><img decoding="async" aria-describedby="caption-attachment-11907" class="size-large wp-image-11907" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Date_validation_check-1024x319.png" alt="date_validation_check" width="634" height="198" srcset="/wp-content/uploads/2016/10/Date_validation_check-1024x319.png 1024w, /wp-content/uploads/2016/10/Date_validation_check-300x93.png 300w, /wp-content/uploads/2016/10/Date_validation_check-768x239.png 768w, /wp-content/uploads/2016/10/Date_validation_check-400x125.png 400w, /wp-content/uploads/2016/10/Date_validation_check.png 1223w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11907" class="wp-caption-text">date_validation_check</p></div>
<p>Now, here comes the real part.</p>
<h3><strong>Setting up Jasmine Framework</strong></h3>
<p>To set Jasmine, we will add a new project to our solution.</p>
<div id="attachment_11908" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Add_new_project.png"><img decoding="async" aria-describedby="caption-attachment-11908" class="size-large wp-image-11908" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Add_new_project-1024x709.png" alt="add_new_project" width="634" height="439" srcset="/wp-content/uploads/2016/10/Add_new_project-1024x709.png 1024w, /wp-content/uploads/2016/10/Add_new_project-300x208.png 300w, /wp-content/uploads/2016/10/Add_new_project-768x532.png 768w, /wp-content/uploads/2016/10/Add_new_project-160x110.png 160w, /wp-content/uploads/2016/10/Add_new_project-400x277.png 400w, /wp-content/uploads/2016/10/Add_new_project-866x600.png 866w, /wp-content/uploads/2016/10/Add_new_project.png 1178w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11908" class="wp-caption-text">add_new_project</p></div>
<p>Now install Jasmine from Nuget Package manager.</p>
<div id="attachment_11909" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Jasmine_Nuget_Package.png"><img decoding="async" aria-describedby="caption-attachment-11909" class="size-large wp-image-11909" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Jasmine_Nuget_Package-1024x570.png" alt="jasmine_nuget_package" width="634" height="353" srcset="/wp-content/uploads/2016/10/Jasmine_Nuget_Package-1024x570.png 1024w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package-300x167.png 300w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package-768x428.png 768w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package-400x223.png 400w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package-1078x600.png 1078w, /wp-content/uploads/2016/10/Jasmine_Nuget_Package.png 1491w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11909" class="wp-caption-text">jasmine_nuget_package</p></div>
<p>Once you are done, the required files would be added to your project. We will be discussing about Jasmine once everything is set. So no worries.</p>
<p>Now please add a new HTML file on your Jasmine project, this is the page where we can see the test cases in actions, and add all the references as follows.</p>
<p>[html]<br />
&lt;!DOCTYPE html&gt;</p>
<p>&lt;html lang=&#8221;en&#8221; xmlns=&#8221;http://www.w3.org/1999/xhtml&#8221;&gt;<br />
&lt;head&gt;<br />
&lt;meta charset=&#8221;utf-8&#8243; /&gt;<br />
&lt;title&gt;Jasmine Spec Runner &#8211; Sibeesh Passion&lt;/title&gt;<br />
&lt;link href=&#8221;content/jasmine/jasmine.css&#8221; rel=&#8221;stylesheet&#8221; /&gt;<br />
&lt;script src=&#8221;http://localhost:12387/Scripts/jquery-3.1.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;http://localhost:12387/Scripts/jquery-ui-1.12.1.min.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/jasmine/jasmine.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/jasmine/jasmine-html.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/jasmine/console.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/jasmine/boot.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;scripts/indextests.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script src=&#8221;http://localhost:12387/Scripts/Index.js&#8221;&gt;&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;</p>
<p>&lt;/body&gt;<br />
&lt;/html&gt;<br />
[/html]</p>
<blockquote><p>Please do not forget to include the js files where we actually written the validations, jquery, jqueryui (if needed). Here indextests.js is the file where we are going to write the test cases.</p></blockquote>
<p>Normally this page is called as Spec Runner, Now you may be thinking what is a Spec? Before going further, there are some terms you must be aware of, there are listed below.</p>
<ul>
<li>Suites</li>
</ul>
<p>A suit is the starting point of a Jasmine test cases, it actually calls the global jasmine function <em>describe</em>. It can have two parameters, a string value which describes the suit, and a function which implements the suit.</p>
<ul>
<li>Spec</li>
</ul>
<p>Like suites, a spec starts with a string which can be the title of the suit and a function where we write the tests. A spec can contain one or more expectation that test the state of our code.</p>
<ul>
<li>Expectation</li>
</ul>
<p>Value of an expectation is either true or false, an expectation starts with the function <em>expect</em>. It takes a value and call the actual one.</p>
<p>You can always read more <a href="http://jasmine.github.io/2.0/introduction.html" target="_blank" rel="noopener">here</a>. Now please run your SpecRunner.html page. If everything is fine you can see a page as below.</p>
<div id="attachment_11910" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page.png"><img decoding="async" aria-describedby="caption-attachment-11910" class="size-large wp-image-11910" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-1024x223.png" alt="jasmine_spec_runner_page" width="634" height="138" srcset="/wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-1024x223.png 1024w, /wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-300x65.png 300w, /wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-768x167.png 768w, /wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page-400x87.png 400w, /wp-content/uploads/2016/10/Jasmine_Spec_Runner_Page.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11910" class="wp-caption-text">jasmine_spec_runner_page</p></div>
<p>So are you all set? Shall we go and write our test cases? Please go to your <em>IndexTest.js</em> file and create a suit and spec as preceding.</p>
<p>[js]<br />
describe(&#8220;Includes validations for index page&#8221;, function () {<br />
var indexPage;<br />
beforeEach(function () {<br />
indexPage = window.indexPage.validationFunctions;<br />
});</p>
<p>it(&#8220;Check for null values&#8221;, function () {<br />
// We are going to pass &#8220;&#8221; (null) value to the function<br />
var retVal = indexPage.isNullValue(&#8220;&#8221;);<br />
expect(retVal).toBeTruthy();<br />
});</p>
<p>});<br />
[/js]</p>
<p>Here the expectation is true and we give toBeTruthy(), now lets go and find whether the test is passed or not. Please run the SpecRunner.html page again.</p>
<div id="attachment_11911" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Test_Jasmine_Specs.png"><img decoding="async" aria-describedby="caption-attachment-11911" class="size-large wp-image-11911" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Test_Jasmine_Specs-1024x199.png" alt="test_jasmine_specs" width="634" height="123" srcset="/wp-content/uploads/2016/10/Test_Jasmine_Specs-1024x199.png 1024w, /wp-content/uploads/2016/10/Test_Jasmine_Specs-300x58.png 300w, /wp-content/uploads/2016/10/Test_Jasmine_Specs-768x149.png 768w, /wp-content/uploads/2016/10/Test_Jasmine_Specs-400x78.png 400w, /wp-content/uploads/2016/10/Test_Jasmine_Specs.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11911" class="wp-caption-text">test_jasmine_specs</p></div>
<p>Now we will write test case for our function <em>isEndDateGreaterStart</em>, if you have noticed the function <em>isEndDateGreaterStart</em>, you can see that there are dependencies (UI elements). Inside of the function, we are getting the values from the UI elements.</p>
<p>[js]<br />
var startDate = new Date(indexPage.validationFunctions.getStartDateSelectedValue());<br />
var endDate = new Date(indexPage.validationFunctions.getEndDateSelectedValue());<br />
[/js]</p>
<p>So in this case, we need to mock this values. It is known as &#8216;Spy&#8217; in Jasmine. We can use a function called <em>SpyOn</em> for this.</p>
<p>[js]<br />
it(&#8220;Spy call for datepicker date validation&#8221;, function () {<br />
//Start date as 2015-03-25<br />
spyOn(indexPage, &#8220;getStartDateSelectedValue&#8221;).and.returnValue(&#8220;2015-03-25&#8221;);<br />
//End date as 2015-03-24<br />
spyOn(indexPage, &#8220;getEndDateSelectedValue&#8221;).and.returnValue(&#8220;2015-03-24&#8221;);<br />
var retVal = indexPage.isEndDateGreaterStart();<br />
expect(retVal).toBeFalsy();<br />
});<br />
[/js]</p>
<p>Here we are giving start date as 2015-03-25 and end date as 2015-03-24 and we know 2015-03-25 &lt; 2015-03-24 is false, so here we are giving expectation as false (toBeFalsy()). Now you are getting an alert as follows right?</p>
<div id="attachment_11912" style="width: 776px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278.png"><img decoding="async" aria-describedby="caption-attachment-11912" class="size-full wp-image-11912" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278.png" alt="alert_in_spyon_jasmine" width="766" height="571" srcset="/wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278.png 478w, /wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278-300x224.png 300w, /wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278-650x485.png 650w, /wp-content/uploads/2016/10/Alert_in_SpyOn_Jasmine-e1475924905278-400x298.png 400w" sizes="(max-width: 766px) 100vw, 766px" /></a><p id="caption-attachment-11912" class="wp-caption-text">alert_in_spyon_jasmine</p></div>
<p>But in testing framework we don&#8217;t need any alerts right? To get rid of this, you must create a spy for window.alert function and add it to the <em>beforeEach</em> so that it can be used for each specs. You can do that as follows.</p>
<p>[js]<br />
window.alert = jasmine.createSpy(&#8220;alert&#8221;).and.callFake(function () { });<br />
[/js]</p>
<p>Once after you add this code, alert message won&#8217;t be thrown. Now please add an another spec with true values (Start date &#8211; 2015-03-25, End date &#8211; 2015-03-26), so that it will return true.</p>
<p>[js]<br />
it(&#8220;Spy call for datepicker date validation toBeTruthy&#8221;, function () {<br />
//Start date as 2015-03-25<br />
spyOn(indexPage, &#8220;getStartDateSelectedValue&#8221;).and.returnValue(&#8220;2015-03-25&#8221;);<br />
//End date as 2015-03-26<br />
spyOn(indexPage, &#8220;getEndDateSelectedValue&#8221;).and.returnValue(&#8220;2015-03-26&#8221;);<br />
var retVal = indexPage.isEndDateGreaterStart();<br />
expect(retVal).toBeTruthy();<br />
});<br />
[/js]</p>
<p>Now you can see all of your specs are passed.</p>
<div id="attachment_11913" style="width: 644px" class="wp-caption alignnone"><a href="http://sibeeshpassion.com/wp-content/uploads/2016/10/Run_all_specs_in_Jasmine.png"><img decoding="async" aria-describedby="caption-attachment-11913" class="size-large wp-image-11913" src="http://sibeeshpassion.com/wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-1024x217.png" alt="run_all_specs_in_jasmine" width="634" height="134" srcset="/wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-1024x217.png 1024w, /wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-300x64.png 300w, /wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-768x163.png 768w, /wp-content/uploads/2016/10/Run_all_specs_in_Jasmine-400x85.png 400w, /wp-content/uploads/2016/10/Run_all_specs_in_Jasmine.png 634w" sizes="(max-width: 634px) 100vw, 634px" /></a><p id="caption-attachment-11913" class="wp-caption-text">run_all_specs_in_jasmine</p></div>
<p>Happy coding!.</p>
<h2><strong>Conclusion</strong></h2>
<p>Did I miss anything that you may think which is needed? Could you find this post as useful? I hope you liked this article. Please share me your valuable suggestions and feedback.</p>
<h2><strong>Your turn. What do you think?</strong></h2>
<p>A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.</p>
<p>Kindest Regards<br />
Sibeesh Venu</p>
]]></content:encoded>
					
					<wfw:commentRss>https://mail.sibeeshpassion.com/writing-javascript-tests-using-jasmine-framework/feed/</wfw:commentRss>
			<slash:comments>7</slash:comments>
		
		
			</item>
	</channel>
</rss>
