The most basic Java Script Interview Questions
 

JavaScript developed by Netscape. JS is a client side as well as a server-side scripting language. It is interpreted programming language as well with object orientated capabilities.

1. How do you create a class in JavaScript?

Answer – There are multiple ways you can create a class in JS. For example

Method 1 – Using functions

// This is a class name

function Flat(aptName, location){

// You can define object properties

this.aptName = aptName;

this.location = location;

this.getLocation = getLocationInfo

}

// The method can be defined as

function getLocationInfo{

return “The location is “ + this.location;

}I

// You can even define function of a class like this

Flat.prototype.getFlatInfo = function() {

alert (“The apartment name is” +   this.aptName + “ and the location is “ + this.location = location);

// Instantiate new object of Flat class

var myFlat = new Flat(“Manjeera”, “Kukatpally”);

// Invoke methods like this

alert myFlat.getLocationInfo();

Method 2 – Using object literals

Var Flat = {

this.aptName = “manjeera”;

this.location = “kukatpally”;

this.getLocation = function() {

return “The location is “ + this.location;

}

}

Apart from using functions, and object literals, you can use object constructor as well to create JavaScript class.

2. What is the difference between ‘==’ and ‘===’?

Answer –       ‘==’ checks for equality only

‘===’ checks for equality and type

For example

false == 0 returns TRUE

false === 0 returns FALSE

3. What is isNan? Give example?

Answer – This would return true of the argument is not a number. For example

isNaN(23) returns false

isNaN(“2/3/2017”) returns true

4. What are the difference comments available in JavaScript?

Answer – There are two types of comments available in JavaScript

A. Single line comments

// This is a single line comment

B. Block comments

/*

This can be used

For block comments

..

*/

5. What are the types used by JavaScript?

Answer – There are six types used in Java Script

Boolean (True and False)

Null (null)

Undefined (undefined)

Number (Integers, floating etc.)

String

Object (Objects, Array, Functions etc.)

6. Is JavaScript a case sensitive?

Answer – Yes, JavaScript is case-sensitive.

7. How can you create an object in JavaScript

Answer – You can use object literal as shown below

var student  = {

name: “Sandeep”,

age: 36

};

Alternatively, you can use below (As explained in question number 1)

var myFlat = new Flat(“Manjeera”, “Kukatpally”);

8. Does JavaScript support exception handling?

Answer – Yes, it does support exception handling by means of try and catch. It supports try, catch, finally, throw etc. keywords to handle exceptions.

9. What is the difference between break and continue?

Answer – Break statement causes program control to exit from the loop.

The continue statement causes program control to continue with next statement.

10. What is the primary difference between ViewState and SessionState?

Answer – ViewState represents a page in session while SessionState is specific to user specific data which can be accessed all across in the web application.

 

 

 

 

 

 

 

 

The five dysfunctions of a team – Book Review
 

I got an opportunity to drive ‘team book reading’ with my highly competent team for one of the very critical facets of team building i.e. “What it takes to be successful as a Team”. The book name is “The five dysfunctions of a team – A leadership fable” which I personally found very interesting hence thought of sharing the summary with you all. Precisely the book talks about the five dysfunctions of a team which restricts the team to be successful. It is very important to understand and overcome them in order to be more effective as a team. The dysfunctions are

Absence of trust
Trust & respect are the foundation stones of any relationship be it a home or office. If the members of the team do not trust each other then they cannot be completely honest with each other.

Hence “Create Trust” by following but not limited to:

  • 360-degree feedback
  • Spend time together
  • Understand each other personal history
  • Believe in each other
  • Be honest

Fear of conflict – Without trust, team members will not have the healthy debates that are necessary to arrive at better thought through decisions.
It’s very important to have open lines of communication (so that everyone is clear & aligned). Always remember

  • Open discussions. Debate leads to a better solution
  • Focus on the issue, not the individual.

Hence “Value Conflict” (It has to be in a healthy way!) by following but not limited to:

  • Straight talk
  • Calling people on behavior traits that demonstrate fear of conflict
  • Identify how we respond
  • Leader leads in behavior

Lack of commitment – If the team has not aligned to a decision then the individual members who did not agree with the final decision will ultimately be less committed to that decision. It is important to know that the “Alignment” is more important than agreement

Hence “Encourage commitment” by following but not limited to:

  • Summaries decisions made in group discussions or meetings
  • Come to consensus — Any decision is better than no decision – Timeboxing decisions.
  • Clarify all scenarios including worst case ones.
  • Talk it loud, hear everyone’s opinion.

Avoidance of accountability – If they are not committed to the course of action, then they are less likely to feel accountable (or hold other people accountable). Lack of clarity of roles & responsibilities and not holding individuals accountable leads to “Avoidance of accountability”
Hence “Promote Accountability” by following but not limited to

  • Open disclosure of goals, standards, and metrics
  • Continuous progress reviews
  • Reward for a team not individual

Inattention to results – If the individuals are not accountable, they are less likely to care about the group results (Instead they would focus on achieving their individual goals).
Hence “Celebrate Results” by following but not limited to:

  • Group declaration of results
  • The reviews to be based on results.
  • The leader should lead in behavior.

Disclaimer “This is a just summary of the book we read – In order to have more details, you are required to read the complete book”.

 

Employee Ranking System (ERS) – Products and Technology
 

What is an employee ranking?

It’s an ordered list of employees from “most valuable” to “least valuable” derived out of the ERS (Employee-Ranking System)

What’s the purpose of an employee ranking?

It provides a logical and consistent framework for employee advancement, recognition, and rewards.  It can unearth and expose significant inequities.  If used on an on-going basis, it can provide valuable insight into employee performance and development trends.

How is “value” defined?

Different definitions make sense in different organizations.  We will consider three major dimensions – competence, the level of contribution, and value to the business.  In other words, how skilled the employees at what they do, how productive are they at what they do, and how irreplaceable are their specific skills or knowledge.  For each dimension, we will consider both “performance to date” as well as the “potential for the future”.  Since performance to date is less ambiguous than future potential, we will give it greater weight. Potentially this would help you to identify core members of your

What process will we use?

We’ll list all employees in a spreadsheet with some basic demographic information, their previous ladder evaluations, and the staff member they report to.  For each of your employees, you will rate them from 1-4 (4 being highest) in the three dimensions described above. You will leverage the details mentioned in this word document below in order to identify rating 1 to 4.  You’ll do that once for past performance and once for future potential for these three areas.  We will then total the numbers and ladder all engineering employees together, assigning a 70% weighting to demonstrated performance and a 30% weighting to future potential. You can download the spreadsheet by clicking on below link

ERS – Products and Technology Ladder

How should I calibrate my evaluations?

Keep in mind that the evaluations are independent of job level and experience.  The idea is to identify “most valuable” to “least valuable” That is, it is perfectly reasonable and generally expected for junior employees to get lower scores than more senior employees.  In fact, when that doesn’t happen, that’s a sign of either a high flying junior employee or an under-performing senior employee.  In addition, you can look at previous years’ rankings to get a sense of overall calibration.  Then, use the supplementary guidance in the sections below.

How precise will all this be?

Don’t worry too much about the precision of the numbers.  Our goal is to get relative ranking right.  The numbers give us a big head start in aligning our reference points and in creating a single merged list for the whole organization.  Once we have a consolidated list, the leadership team can ensure right people are in the right place.

Any other helpful instructions?

  • Please be careful not to break any of the formulas in the spreadsheet.
  • If you see errors in any cell, please highlight the cell and make the appropriate correction.
  • For the Rating column, enter your best estimate of the numeric performance rating (from 1-5) that the employee will receive this year or whatever your rating system is.
  • For the Promotion and the Performance Improvement Plan columns, enter a “Y” if you believe the employee should be on one of these tracks for the current year. Otherwise, you can leave the column blank.

The ranking would be derived from three core factors

  1. 1. Competence
  2. 2. Contribution
  3. 3. Value to business

Competence

Areas to consider:

  • – Breadth and depth of knowledge and skills
  • – Leadership and innovation, applied to people, processes, and projects
  • – Problem-solving ability
  • – Technical, business, communication, interpersonal skills

Rating 4:
Has mastered all required skills. Demonstrates strong leadership in one or more areas (e.g., technical, project management, process, etc.).  Consistently works to leverage skills for team and larger organization success.

Rating 3:    
Often operates above the norm, with advanced skills in some areas. Often expends extra effort to help meet goals. Has demonstrated leadership in one or more areas.

Rating 2:   
Has all basic skills for job category and uses them effectively to meet project goals.

Rating 1:   
Needs additional skills development to meet job requirements and to attain project goals. May demonstrate inconsistent achievement of task objectives and project goals.

Contribution

Areas to consider:

  • -Ability to meet commitments
  • – Overall productivity and volume of output
  • – Early communication of problems and contribution to workarounds that meets business goals
  • – Versatility – willingness and ability to adapt to new tasks
  • – Teamwork – willingness and ability to help others
  • – Leadership skills such as architecture, project management, change management, communication, and mentoring
  • – Ability to motivate others, manage self, and demonstrate initiative.

Rating 4:  
Someone who has a lot of initiative, is a  leader across the organization, and has outstanding productivity.

Rating 3:   
Someone who excels in 1 or 2 of these dimensions but not all 3.

Rating 2:   
Someone who delivers what is expected (i.e. does not take much initiative to do more), is a team player but not a leader, and has productivity as expected.

Rating 1:    
Someone who is below expectations in one or more of these dimensions.

Value to the Business

Areas to consider:

  • – Knowledge and skills as mapped to needs of the business
  • – Extra points here for unique skills we need

Rating 4:    
A critical person on a high profile project, creating a vision or blueprint for the project or accomplishing critical business objectives.  Without this person, current and future objectives would not be accomplished.

Rating 3:  
A core person on a high profile project.  Without this person, current and future objectives would be impaired.

Rating 2: 
Could be replaced without significant negative impact to the business.

Rating 1:     
The negative impact to the business. Drains resources and causes objectives not to be accomplished.

 

Bloated Domain Objects And CQRS (Command, Query Responsibility Segregation)
 

Problem of Bloated Domain objects

In business software applications, the domain objects (entities) are used to represent the business domain. As the application grows and adds more business logic, the service layer, mappers and other patterns gets applied. Often this leads to domain object becomes bloated and the related components become huge & un-maintainable.

CQRS solves the common problem of having a bloated Domain objects. The domain objects get bloated largely because of bounded context. The series of contexts which makes developers think that a single domain object is sufficient to handle all the related things. For example, a large Invoice object for handling Invoice, Shipment and handling change of address for customer . But in reality, these contexts (invoicing, shipment and change) need not be related to same Invoice entity.

What is Command, Query Responsibility segregation (CQRS)?

In order to simplify the Domain objects, CQRS proposes to have two types of domain entities.

  • those serving the command (ordering/assertion services)  – For example, SaveCustomer, CreateInvoice, ShipProduct etc
  • those serving a Query (request) – examples include GetCustomerAddress, SearchCustomer etc

With this separation, the complexity (number of fields, methods) of entities used becomes simplified. And hence the Data mapper layers & the service layers becomes more simplified.

Where can I use CQRS?

  • Largely complex system: Applying CQRS on a simple CRUD operation based system is a over kill. When there is a domain heavy system, like banking and financing systems, LOB applications where business logic, lots of boundary conditions are heavy. Where it makes DDD (Domain driven design) provides high value.
  • Situations where you will apply Microservices, Eventual consistency and Event Sourcing. When we have separation of concerns using CQRS, the microservices becomes much simpler to design and maintain. With Event sourcing we are focused on getting the data (query) from other related sources and is what CQRS propagates.

Final words

CQRS is a carefully thought out pattern for simplifying large and complex systems. And it should not be applied for simple green field applications. Do let me know what you think.

Top 100 Agile Blogging Websites in the world
 

Top 100 Agile Blogs websites

Below is the top 100 Agile websites list published by AgileChamps team. The process followed to identify top 100 sites is:-

  1. Identified few core keywords used for Agile.
  2. These keywords are used against the majority of top search engines.
  3. The websites coming on first few pages are identified.  Approx. 1200 plus websites are shortlisted.
  4. Identified Alexa Rank for all of them.
  5. All the websites under 15 million ranks are reviewed individually.
  6. The websites which are heavy centric on Agile are marked and rest are removed.
  7. At this point, top 200 websites are shortlisted for final review and research. The top 100 are picked after spending a good time with each and every website.

The list may not be 100% perfect but it should be close as there are chances that some of the good websites on Agile are missed. If you think, you have an Agile Blogging site which is not listed here, please do mention in the comment section with Alexa rank and we would include that in below list.

Rank Agile Blogging Site Alexa Rank Comments
1 http://softwaredevelopmenttoday.com/ 1030 Improving the world with software
2 http://agilescout.wpengine.com/ 3078 Agile Software Development News
3 http://agile.dzone.com/ 4167 Agile and Technology
4 http://www.infoworld.com/ 11991
5 http://blogs.msdn.com/b/jmeier/ 12181
6 http://martinfowler.com/ 29470
7 http://scrumalliance.org/ 36377
8 http://geekswithblogs.net/Default.aspx 36908 Agile and Technology
9 http://blog.scrum.org 62603
10 http://www.mountaingoatsoftware.com/ 65325
11 http://www.versionone.com 106619
12 http://www.lean.org/ 143610
13 http://blog.xebia.com 157824
14 http://www.romanpichler.com/ 180494
15 http://www.allaboutagile.com/ 181443
16 http://agilewarrior.wordpress.com/ 257143
17 http://scrummethodology.com/ 269615
18 http://blog.crisp.se/henrikkniberg 279696
19 http://www.torbenrick.eu/blog/ 286285
20 http://www.scruminc.com/ 327659
21 http://www.shmula.com/ 345374
22 http://www.solutionsiq.com/ 359293
23 http://tynerblain.com/blog/ 392184
24 http://www.leadingagile.com/ 396993
25 http://management.curiouscatblog.net/ 420641
26 http://www.agileforall.com/ 451259
27 http://www.marcusoft.net/ 473266
28 http://alistair.cockburn.us/Agile+development 505811
29 http://www.agile42.com 529073
30 http://services.leankanban.com 540509
31 http://www.agileweboperations.com/ 563971
32 http://agilescout.com/ 574286
33 https://age-of-product.com 600556
34 http://www.jrothman.com/blogs/ 608049 Management and Agile
35 http://blog.retrium.com 681480
36 http://tastycupcakes.org/ 736304
37 http://www.netobjectives.com 767821
38 http://jamesshore.com/ 768661
39 http://ronjeffries.com/ 791006
40 http://www.klocwork.com 799097
41 http://www.personalkanban.com/ 806918
42 http://www.agileadvice.com/ 881368
43 http://benlinders.com 908226
44 http://www.scrumexpert.com/ 941122
45 http://brodzinski.com/ 950714
46 http://blogs.agilefaqs.com 979367
47 http://herdingcats.typepad.com 995606
48 http://scrumology.com/ 1105693
49 http://agilepainrelief.com/ 1210659
50 http://blog.3back.com/ 1300016
51 http://leadinganswers.typepad.com 1309169
52 http://www.implementingscrum.com/ 1340427
53 http://kenschwaber.wordpress.com/ 1454803
54 http://testobsessed.com/ 1567560
55 http://www.agilitrix.com/ 1590376
56 http://lithespeed.com/ 1674920
57 http://lisacrispin.com/ 1705271
58 http://guntherverheyen.com 1879037
59 http://www.betterprojects.net/ 1917210
60 http://agilesoftwaredevelopment.com/ 1917606
61 http://www.agile-ux.com/ 1948198
62 http://leansoftwareengineering.com/ 2054154
63 http://agilecoach.typepad.com 2064719
64 http://www.agilistapm.com/ 2302141
65 http://borisgloger.com/ 2332692
66 http://www.estherderby.com/ 2377232
67 http://www.makinggoodsoftware.com/ 2522442
68 http://www.growingagile.co.za 2552857
69 http://www.ontheagilepath.net 2578280
70 http://www.cindyalvarez.com/ 2585993
71 http://www.jbrains.ca 2606431
72 http://www.scrum-breakfast.com/ 2632324
73 http://www.dkrimmer.de 2667951
74 http://leanandkanban.wordpress.com/ 2726139
75 http://blog.agilegamedevelopment.com/ 2726568
76 http://www.gettingagile.com/ 2729011
77 http://brainslink.com/ 2808821
78 http://blog.oikosofy.com 2893584
79 http://availagility.co.uk/ 3117999
80 http://www.leanessays.com/ 3134021
81 http://kellycrew.wordpress.com/ 3194994
82 http://scrumcoaching.wordpress.com/ 3397983
83 http://www.agilechamps.com 3420233 Based on real time experiences. Agile becomes simple.
84 http://www.coachingagileteams.com/ 3493804
85 http://www.derekhuether.com 3499622
86 http://www.axisagile.com.au 3630517
87 http://www.softwareresults.us/ 3658561
88 http://indigoblue.co.uk 3671917
89 http://www.agiletrainings.eu 3740017
90 http://hanoulle.be/ 3782502
91 http://lmsgoncalves.com 4120325
92 http://fragile.org.uk/ 4235666
93 http://theagileexecutive.com/ 4479652
94 http://scalingsoftwareagility.wordpress.com/ 4543469
95 https://scrumfamily.wordpress.com/ 4603896
96 http://www.tinypm.com/blog/ 4815953
97 http://catenary.wordpress.com/ 5292497
98 http://www.agilecoach.ca/ 5352264
99 http://www.thoughtclusters.com/ 5547969
100 http://agilemindstorm.com/ 6605622

I would really appreciate if you can provide a link to this blog to your website if your website is listed above.

50 Web Performance Tips and Tricks
 

I came across the below video on the web performance improvement tips and tricks. This is fantastic.

http://channel9.msdn.com/Events/Build/2012/3-132

In this video, Jatinder talks about Six fundamental principles for improving web application performance. He also talks a lot about how we go about Decreasing CPU time and increasing parallelism on the client machine to achieve faster web performance.

While I went through the video, I captured all the tricks he talks about. And thought will be useful for others while they watch it. Please find below the tricks.

Quickly respond to network request

  • Avoid 3XX Redirections (63% of top websites use redirect)
  • Avoid Meta refresh
  • Minimize Server time for Requests
  • Use Content distribution Networks (CDN)
  • Maximize concurrent connections.
  • Reuse connections – don’t sent connection close.
  • Know your other servers – you are only fast as your weakest link
  • Understand your network timing

Minimize bytes downloaded

  • GZIP Compression Network traffic
  • Persist application resources locally (Windows 8 applications)
  • Cache dynamic resources in the application Cache (html5 app cache)
  • Provide cacheable content
  • Send Conditional request
  • Cache Data requests (jQuery AJAX calls)
  • Standardize File name capitalization convention.

Efficiently structure markup

  • Load pages in latest browser mode
  • Use http header to specify legacy IE mode
  • Link CSS in the top of the page header, never on the bottom.
  • Avoid using @import of hierarchical styles
  • avoid embedded and inline CSS
  • Only include necessary styles in the page.
  • Always link JS at the end of the page.
  • Avoid linking JS in the header (use the defer & async attribute)
  • Avoid Inline JS
  • Remove Duplicate code (52% of the web have duplicate code
  • Standardize on a single framework

Optimize your media usage

  • Avoid death by too many images
  • If possible use Image Sprites
  • Use png image file format
  • Use Native image resolutions
  • Replace Images with CSS3 Gradients, border Radius
  • Leverage CSS3 Transforms
  • Use Data URI’s for Small Single view images
  • Avoid complex SVG paths
  • Video : Use preview images
  • Minimize media plugin usage
  • Proactively download Future media

Write Fast JavaScript

  • Stick to Integer math (Math.Floor)
  • Minify your JavaScript
  • Initialize JavaScript on Demand
  • Minimize your DOM Interactions
  • Built in DOM methods always more efficient (firstchild, nextsibling methods are faster)
  • Use Selectors for Collection access (document.querySelectorAll)
  • Use .innerHTML to construct your page
  • Batch your markup changes
  • Maintain smaller DOM (less than 1000 elements)
  • Json always faster than XML
  • Use Native Json methods
  • Use regular expressions Sparingly

Know what your app is doing

  • Understand JavaScript Timers (setTimeout, SetInterval)
  • Combine Application Timers
  • Ensure dormant timers are not running
  • Align timers to display Frame (16.7)
  • Use window.requestAminationFrame(renderLoop) for Animations
  • Know when your application is visible (document.hidden, Visibilitychange (event))

Conclusion

The web optimization is not easy and needs exhaustive deep look and hopefully this check list helps while optimizing your pages. Enjoy coding high performing applications. If you have more tips please provide them in the comments.

 

Micro-Services, Eventual Consistency and Event sourcing patterns
 

Microservices is a really becoming a famous architectural pattern that most of the new software written these days, just apply them. One of the most important differentiation between the traditional web services and micro services pattern is the amount of common stuff across different subject areas. This calls for a discussion on how Eventual Consistency pattern is mandatory for successfully implementing micro services.

Micro-Service Pattern

Generally in a micro-service pattern, the API’s are split in to small subject areas. For example for a CRM application, the subject areas are

  • Customer information – like name, address, email, phone
  • Appointment information – which customer, sales person, when, where
  • Relationship management – sales/manager, what products, interests
  • Campaign data – offers, deals etc

Then micro-services are built for each of the subject areas.  The microservices are logically and physically separated from each other. ie there is no sharing (code, database, component etc) between any of these micro services of these subject areas. Pictorially its looks something like this.

Applying Eventual Consistency Pattern

In Micro-services, there is no data that is shared across the micro services. In order to synchronize the data across these isolated storages of these services, we need to apply the eventual consistency pattern. You can read more about applying the pattern correctly here. The simpler way we can achieve consistency across these micro-services is through Event Sourcing pattern.

Event Sourcing

Event sourcing is a process of capturing application state changes in the form of events.  An example of events are customer created, customer updated, Deal created, etc.  Other systems listen to these events and they take relevant action. You can read more about event sourcing here.

Conclusion

Event sourcing is the new way of storing changes to systems and help in making micro-services eventually consistent. These patterns together form well maintainable, reliable and scalable systems in the modern world.

BDD (Behavior Driven Development)
 

In the previous article we looked at how to do Test Driven Development (TDD) while doing the XP (Extreme Programming). In XP, the implementation of the tasks are done in the steering phase of the iteration planning. One of the tenets of the steering phase is “functional tests are run”. In this article we will see how to create functional tests using Behavior driven development (BDD) and its benefits.

Following are the some of the benefits of automated functional tests.

  • Functionality experienced by the User is tested
  • Saves testing time for the developers
  • Test in every environment (Dev, QA, Stage) without much effort
  • Generates confidence in every stake holder

Tools required for doing BDD in .Net

There are various tools available to do BDD in .Net. I have listed few of them below

SpecFlow is one of the most popular tools used in the .Net/C# community. And in this blog lets use the same. The tool comes as a Visual Studio Extension and can be downloaded directly from VS.

Creating a SpecFlow Project

Once SpecFlow extension is installed, the template required for doing BDD will be installed.

  • Create a simple “Class Library” Project in Visual studio
  • In the project, create a SpecFlow Feature file

Selecting the test framework

Before we Create/execute the scenario, we need to wire the SpecFlow with a compatible test framework. To do that we need to make changes to the app.Config file of the project.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
  </configSections>
  <specFlow>
    <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
  <!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
    <unitTestProvider name="xUnit" />
  </specFlow>
</configuration>

In this example we are using XUnit as the testing framework. SpecFlow supports a series of testing frameworks and more details can be found here.

Creating the Behavior

Now, let us look at how to create a functional test using behavior driven approach. Let’s consider the following story while creating a POS (point of sale) application for a super market.

“As a Supermarket POS app developer,  i would like the API to Give the total amount while billing so that I can wire up API against the UI.

Let’s write the Behavior required in order to implement the above API requirement .

Feature: SuperMarketProductsAPI
	As a Supermarket Biller 
	i would like the API to
	Give the total amount while billing
@SmokeTest
Scenario: Find the total amount while billing
	Given Shopping cart is filled with all the items required by consumer
	And Campaign information for the month is available in the system
	When I pass the cart to create bill API
	Then the total bill amount should be calculated

The above specification is written using the custom language (testing DSL) create by the specflow.org. (Please read about what is DSL here.)

There are 2 parts to the above Specflow specification

  • Feature – Denotes bigger context (description/story) of the application
  • Scenario – Specific workflow or behavior of the system under the feature. Each scenario has the following sub-parts
    • Given, And – describes what we already assumed available
    • When – The specific action which will trigger the workflow/behavior
    • Then  – expected behavior

 

Creating step definitions

When we run the unit test corresponding to the above test we it will fail as there are no definitions corresponding to the above scenarios.

Now Right Click on the feature file and select “Generate step Definitions”

You will see the pop-up like below, select “Generate” and then “Save” the file.

The file will have the details about “what SpecFlow should do when test is executed”.

using System;
using TechTalk.SpecFlow;

namespace SuperMarketFunctionalTests
{
    [Binding]
    public class SuperMarketProductsAPISteps
    {
        [Given(@"Shopping cart is filled with all the items required by consumer")]
        public void GivenShoppingCartIsFilledWithAllTheItemsRequiredByConsumer()
        {
            ScenarioContext.Current.Pending();
        }
        
        [Given(@"Campaign information for the month is available in the system")]
        public void GivenCampaignInformationForTheMonthIsAvailableInTheSystem()
        {
            ScenarioContext.Current.Pending();
        }
        
        [When(@"I pass the cart to create bill API")]
        public void WhenIPassTheCartToCreateBillAPI()
        {
            ScenarioContext.Current.Pending();
        }
        
        [Then(@"the total bill amount should be calculated")]
        public void ThenTheTotalBillAmountShouldBeCalculated()
        {
            ScenarioContext.Current.Pending();
        }
    }
}

When you build the project and execute the test corresponding to this, it will fail. This is because none of the parts of the test (given, when, then) are having implementation.

Writing code to make it work

Now that the behavior has been created, we are good to validate that with the team and implement the code/functionality corresponding to the requirement. Of course using best coding practices like TDD 🙂

Making the behavior test pass

In order to make the behavior test pass we need to write the implementation in the “Step Definition” file.

namespace SuperMarketFunctionalTests
{
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using System.Net.Http;
    using TechTalk.SpecFlow;
    using Xunit;

    [Binding]
    public class SuperMarketProductsAPISteps
    {
        Product P1 = new Product { Name = "test1", Cost = 5 };
        Product P2 = new Product { Name = "test2", Cost = 10 };
        ShoppingCart cart;
        List<Campaign> campaign;
        Bill bill;
        [Given(@"Shopping cart is filled with all the items required by consumer")]
        public void GivenShoppingCartIsFilledWithAllTheItemsRequiredByConsumer()
        {
            cart = new ShoppingCart { Products = new List<Product> { P1, P2 } };
        }
        
        [Given(@"Campaign information for the month is available in the system")]
        public void GivenCampaignInformationForTheMonthIsAvailableInTheSystem()
        {
            campaign = new List<Campaign> { new Campaign { product = P1, discount = 1 } };
        }
        
        [When(@"I pass the cart to create bill API")]
        public void WhenIPassTheCartToCreateBillAPI()
        {
            var client = new HttpClient();
            var response = client.PostAsync("http://myapi.supermarket.com", new StringContent(JsonConvert.SerializeObject(cart))).Result;
            var output = response.Content.ReadAsStringAsync().Result;
            bill = JsonConvert.DeserializeObject<Bill>(output);
        }
        
        [Then(@"the total bill amount should be calculated")]
        public void ThenTheTotalBillAmountShouldBeCalculated()
        {
            Assert.True(bill.totalAmount == 14);
        }
    }
}

Once the code is there we can see the behavior test pass.

Conclusion

BDD is very powerful way of ensuring high code quality in conjunction with business requirement. In Extreme programming (XP) , BDD is considered to be a very important practice where functional tests are mandated to run at least once during the iteration.  Is BDD/Functional tests helping your team/business in achieving success or not ? Do let us know your thoughts.