Why Dependency Injection?

Hi Friends,

I have been recently asked by one of my book readers on twitter, why you applied Dependency Injection (DI) in controller? Below is the tweet for the same. Below is the glimpse of the same.

Continue reading “Why Dependency Injection?” »

1,859 total views, no views today

Building FrontEnd App with Yeoman – 3rd Part

Hi Friends,

In this section, we’ll delve further and enhance the app where we stopped last time. Now, let us go ahead and improvise the UI a bit, so that it feels good and look good. In order to get started, I will make use of some bootstrap templates which you can refer here @ Bootstrap. Now, from here i will pick Cyborg theme as shown below in the screen shot.

31th

From here, I will just go ahead and download the css file and save in my bower components as shown below in the screen shot. I could have placed it in my app styles folder as well, but there my fonts and other dependent items are not there, hence it’s good to have consistency and place it at one place. Here, i have downloaded two themes cyborg and superhero.

33rd

Then, i have commented the initial reference of bootstrap and referenced new one as shown below.

With the above change in place, it produced the below theme.

34th

Now, it feels better. I have also improvised a bit in the movies template with the below snippet.

One more change i have done for menu highlighting with the minor change as shown below.

With the above change in place, it will look like as shown below.

35th

36th

Now, let us go ahead and create Movies controller to put some data in. For doing that, I have used my yo generator to do the same.

38th

37th

39th

Therefore, this is the benefit of using yo generator. Out of the box, it gave me test file as well. Now, let us go ahead let us put some data in there to display on the page. Off-course currently, it will be static data. Later we will see how to couple the same with data fetched from the server. By the way, below snippet is the default one created by generator.

Looks ok to me. But, I don’t need these stuffs, hence I will modify the same and make some necessary changes as shown below.

Now, i need to do corresponding view changes

With the above change in place, it will produce the below result. Although the page doesn’t look super impressive, but that’s ok. UI is least bothered for now.

40th

41th

I have also added two more views for Login page and Register as shown below in the screen shot.

login_adv

register_adv

Functionality of this, we will see in coming section. Till then stay tuned and Happy coding.

Thanks,
Rahul Sahay
Happy Coding

2,498 total views, 1 views today

Writing Unit Tests against actual legacy data

Hi Friends,

In today’s discussion, we will talk about writing Unit Tests, but it is not about how to get started with Unit Tests. Rather it is about, if you have a scenario where in you need to construct data set which is very primitive and it needs lot of work to construct even mock data. So, the best thing which i find is you can collect the actual data either from SOAP tool, if it is some kind service response and have the same in xml. And then you can write Unit Tests against that like shown below.

For one of the scenarios. Below, I have collected and constructed my XML.

<?xml version="1.0" encoding="utf-8" ?>
<CustomerResponseDTO>
  <ContractList>
    <Contract>
      <ContractNumber>530000000112</ContractNumber>
      <ContractIdPK>713343129248515901</ContractIdPK>
      <CurrencyType>1000001</CurrencyType>
      <CurrencyValue>USD</CurrencyValue>
      <FrequencyModeValue>B</FrequencyModeValue>
      <BillingValue>10 Days Inv</BillingValue>
      <ServiceProvId>1</ServiceProvId>
      <CompanyNumber>19</CompanyNumber>
      <IssueLocation>US</IssueLocation>
      <ContractLastUpdateDate>2015-05-10 16:14:45.158</ContractLastUpdateDate>
      <ContractLastUpdateUser>mdmadmin</ContractLastUpdateUser>
      <ContractLastUpdateTxId>626143129248478201</ContractLastUpdateTxId>
      <AgreementName>MaxWell</AgreementName>
      <ComponentID>1000944</ComponentID>
      <ContractExtension>
        <CreditLimit>222</CreditLimit>
        <ShippingChargeFlag>Y</ShippingChargeFlag>
        <TaxableFlag>Y</TaxableFlag>
        <CustomerClass>SA</CustomerClass>
        <CreatedBy>DSA</CreatedBy>
        <LinkNumDesc>Test</LinkNumDesc>
        <SalesPerson/>
        <ModifyBy>XMODIFY_BY</ModifyBy>
      </ContractExtension>
      <AdminNativeKey>
        <AdminNativeKey>
          <adminNativeKeyIdPK>712243</adminNativeKeyIdPK>
          <adminContractId>530000</adminContractId>
          <adminFieldNameType>CustomerAccountNumber</adminFieldNameType>
          <adminFieldNameValue>123456</adminFieldNameValue>
          <contractId>7133431</contractId>
          <nativeKeyLastUpdateDate>2015-05-10 16:14:45.266</nativeKeyLastUpdateDate>
          <nativeKeyLastUpdateUser>mdmadmin</nativeKeyLastUpdateUser>
          <nativeKeyLastUpdateTxId>6261431</nativeKeyLastUpdateTxId>
        </AdminNativeKey>
      </AdminNativeKey>
    </Contract>
  </ContractList>
</CustomerResponseDTO>

Then, you can write test case like shown below:-

[TestMethod]
        [DeploymentItem(CILXMLFile)]
        public void Should_Have_Customer_Number()
        {
            var actual = GetSampleData();
            //Assert
            Assert.AreEqual(530000, actual.CustomerNumber);
        }

        [TestMethod]
        [DeploymentItem(CILXMLFile)]
        public void Should_Have_Company_Name()
        {
            var actual = GetSampleData();
            //Assert
            Assert.AreEqual("MaxWell", actual.CompanyName);
        }

Then, you can get the GetSampleData() like shown below.

const string XMLFile = @"TestData/TestData.xml";
        private static T DeserializeTestData<T>(string xmlPath) where T : class
        {
            var serializer = new XmlSerializer(typeof(T));

            using (var reader = new StreamReader(xmlPath))
            {
                return (T)serializer.Deserialize(reader);
            }
        }

        private Adapers.Customer GetSampleData()
        {
            //Arrange
            
            var customerResponseDto = DeserializeTestData<CustomerResponseDTO>("TestData.xml");

            Mock<ICustomerSearchServiceWrapper> mock = new Mock<ICustomerSearchServiceWrapper>();



            mock.Setup(
                      obj =>
                          obj.GetCustomer(It.IsAny<GetCustomerRequestDTO>(), It.IsAny<PagingInput>(),
                              It.IsAny<ClientApplicationInfo>()))
                  .Returns(customerResponseDto);

            var objectUnderTest = new TestSearchServiceAdapter(mock.Object,new Mock<IConfigurableSettings>().Object);
            //Act

            var actual = objectUnderTest.GetAddressDetails("1234567890", "US", "BLG");
            return actual;
        }

With the above changes in place, when i run the same, it will produce the below result.

5th

Thanks for joining me.

Thanks,
Rahul Sahay
Happy Coding

1,296 total views, 1 views today

Fluent Assertions

Hi Friends,

Today, i will talk about one of the patterns which i usually use while writing unit tests. Apart from MOQ library, i also use Fluent Assertions(http://www.fluentassertions.com/). You can search for the same in nuget package manager and install it in the test project. Out of the box, fluent assertions give tons of extensions method which help to easily write assertions on the actual like shown below. In the below example, i am just running the test against one sample string of my name.

1st

Now, when i complete this test, it will look like

 [TestMethod]
        public void CheckStringValue()
        {
            string actual = "Rahul Sahay";
            actual.Should().StartWith("Ra").And.EndWith("ay");
        }

When, i run the same it will produce the below result.

2nd

Similarly, To verify that a collection contains a specified number of elements and that all elements match a predicate, you can test like shown below.

 [TestMethod]
        public void CheckCollection()
        {
            IEnumerable collection = new[] { 1, 2, 3,4,5 };
            collection.Should().HaveCount(6, "because I thought I put 5 items in the collection");
        }

Now, when i run the above test, it will fail. And this will fail for a valid reason. But, look at the error message returned by the same.

3rd

Let, me show the same against one of the infrastructure code where i am using the same.

[TestMethod]
        public void MovieNameTest()
        {
            IEnumerable<Movie> movie;
            var mockMovieRepository = MovieRepository(out movie);

            mockMovieRepository.Setup(obj => obj.GetMovies()).Returns(movie);

            IMovieService movieService = new MovieManager(mockMovieRepository.Object);

            IEnumerable<MovieData> data = movieService.GetDirectorNames();

            data.Should().HaveCount(4, "because we put these many values only");


        }

Now, it has one dependency on MovieRepository(out movie). Basically, this is my arrange.

  private static Mock<IMovieRepository> MovieRepository(out IEnumerable<Movie> movie)
        {
            Mock<IMovieRepository> mockMovieRepository = new Mock<IMovieRepository>();

            //Mock return as GetMovies returns the same, so we are not going to hit db
            //we are going to return mocked up entity
            movie = new Movie[]
            {
                new Movie()
                {
                    MovieName = "Avatar",
                    DirectorName = "James Cameron",
                    ReleaseYear = "2009"
                },
                new Movie()
                {
                    MovieName = "Titanic",
                    DirectorName = "James Cameron",
                    ReleaseYear = "1997"
                }
            };
            return mockMovieRepository;
        }

When, i run the above test, it will again throw similar error because count is 2 and i am checking for 4.

4th

Thanks for joining me. I hope you like it.

Rahul Sahay,
Happy Coding

2,009 total views, 1 views today