Thursday, 9 March 2023

Moq using Nunit

 In software testing, mocking is a technique used to simulate parts of a system that are not yet implemented or are difficult to test. NUnit is a popular unit testing framework for .NET applications that provides support for mocking using various third-party libraries such as Moq, NSubstitute, and RhinoMocks. Here's an example of how to use Moq to create a mock object for a C# class:

csharp
// The class we want to mock public class MyClass { public virtual int GetNumber() { return 42; } } // The test class [TestFixture] public class MyTestClass { [Test] public void TestMethod() { // Create a mock object of MyClass var mockMyClass = new Mock<MyClass>(); // Set up the behavior of the mock object mockMyClass.Setup(x => x.GetNumber()).Returns(5); // Use the mock object in our test var result = mockMyClass.Object.GetNumber(); // Verify that the mock object was called mockMyClass.Verify(x => x.GetNumber(), Times.Once()); // Assert that the result is what we expect Assert.AreEqual(5, result); } }

In this example, we create a mock object of the MyClass class using the Mock<MyClass> the class provided by Moq.

We then set up the behavior of the mock object using the Setup method, which specifies that when the GetNumber the method is called, it should return the value 5. Finally, we use the mock object in our test and verify that the GetNumber the method was called once and the result is what we expect using the Verify and Assert methods.

Note that when using Moq, you need to mark any methods you want to mock as virtual, so that the mock object can override them.

Unit Testing C# with NUnit

 NUnit is a popular open-source unit testing framework for .NET languages such as C# and VB.NET. It allows developers to write and run automated tests to verify the behavior of their code. NUnit supports a wide range of assertions, test fixtures, and test runners, making it a powerful tool for unit testing.

NUnit supports various features such as:

  1. Test fixtures: A test fixture is a collection of unit tests that can be run together. NUnit provides a set of attributes that can be used to define test fixtures.

  2. Test cases: NUnit allows developers to define test cases with different parameters, which helps to ensure that the code works correctly under different scenarios.

  3. Assertions: NUnit provides a wide range of assertions, which can be used to test different conditions in code. Some of the commonly used assertions include Assert.AreEqual, Assert.IsTrue, and Assert.IsFalse.

  4. Test runners: NUnit provides a command-line test runner as well as integration with various IDEs, including Visual Studio, which makes it easy to run tests and view results.

Overall, NUnit is a powerful and flexible unit testing framework that helps developers to write high-quality code by ensuring that the code works as expected.


here's an example of a test case for a simple calculator class that adds two numbers:

using NUnit.Framework; [TestFixture] public class CalculatorTests { private Calculator calculator; [SetUp] public void Setup() { // Arrange calculator = new Calculator(); } [Test] public void Add_TwoPositiveNumbers_ReturnsSum() { // Act int result = calculator.Add(2, 3); // Assert Assert.AreEqual(5, result); } [Test] public void Add_OneNegativeOnePositiveNumber_ReturnsDifference() { // Act int result = calculator.Add(-2, 3); // Assert Assert.AreEqual(1, result); } }

In this example, we have a CalculatorTests class that contains two test cases:

  1. Add_TwoPositiveNumbers_ReturnsSum: This test case verifies that the Add method of the Calculator class correctly adds two positive numbers and returns their sum. The test first creates a new instance of the Calculator class in the Setup method (which is called before each test), then calls the Add method with the arguments 2 and 3, and finally uses the Assert.AreEqual method to check that the result is 5.

  2. Add_OneNegativeOnePositiveNumber_ReturnsDifference: This test case verifies that the Add method correctly handles one positive and one negative number by returning their difference. The test follows the same steps as the first test, but with the arguments -2 and 3, and the expected result of 1.

By running these tests, we can ensure that the Calculator class works as expected and handles different input scenarios correctly.

Wednesday, 11 May 2022

AngularJS vs. Angular 2 Vs. Latest Angular Version

 Let's UnderStand the difference between  AngularJs and Angular Versions

Difference Between AngularJs and Angular Versions

AngularJS to Angular, Angular includes both version 2 and version 4, and so on... We compare Architecture, Language, Expression Syntax, Mobile Support, and Routing.

1. Architecture

AngularJS

The architecture of AngularJS is based on the model-view-controller (MVC) design. The model is the central component that expresses the application's behavior and manages its data, logic, and rules. The view generates an output based on the information in the model. The controller accepts input, converts it into commands, and sends the commands to the model and the view

Angular

Angular uses components and directives. Components are directives with a template.

Angular 2 

In Angular 2, controllers and $scope were replaced by components and directives. Components are directives with a template. They deal with a view of the application and logic on the page. There are two kinds of directives in Angular 2. These are structural directives that alter the layout of the DOM by removing and replacing its elements, and attributive directives that change the behavior or appearance of a DOM element.

In Angular 4, the structural derivatives ngIf and ngFor have been improved, and you can use if/else design syntax in your templates.   

 2. Language

AngularJS

AngularJS is written in JavaScript. 

Angular versions

Angular uses Microsoft’s TypeScript language, which is a superset of JavaScript. This has advantages like type declarations, and the benefits of ES6, like iterators and lambdas

Angular 4 is compatible with the most recent versions of TypeScript which have powerful type checking and object-oriented features. 

3. Expression Syntax

AngularJS

To bind an image/property or an event with AngularJS, you have to remember the right ng directive.

Angular versions

Angular focuses on “( )” for event binding and “[ ]” for property binding.

4. Mobile Support

AngularJS was not built with mobile support in mind, but Angular, Angular 2, 4, and so on.... feature mobile support.

5. Routing

AngularJS uses $routeprovider.when() to configure routing while Angular uses @RouteConfig{(…)}. 

6. Performance 

AngularJS was originally developed for designers, not developers. Although there were a few evolutionary improvements in its design, they were not enough to fulfill developer requirements. The later versions, Angular 2 and Angular 4, have been upgraded to provide an overall improvement in performance, especially in speed and dependency injection. 

  • Speed

By providing features like 2-way binding, AngularJS reduced the development effort and time. However, by creating more processing on the client-side, page load was taking considerable time. Angular2 provides a better structure to more easily create and maintain big applications and a better change detection mechanism. 

  • Dependency Injection

Angular implements unidirectional tree-based change detection and uses the Hierarchical Dependency Injection system. This significantly boosts the performance of the framework.



AngularJS (Angular 1) is totally different from the later versions. And the reason for this is that there is a complete rewrite of the Angular framework between Angular 1 and Angular 2.

Angular 2 was released in the year 2016 and it was rewritten from the ground up. So the basic reason for developing Angular 2 is to fix all the issues that Angular 1 had.

since then that initial release of Angular 2 we had a couple of other versions as well i.e. Angular 4, Angular 5…….and Angular 9...12.

Angular 3 was skipped due to internal reasons.

Since we have all these versions of Angular till now so does it mean Angular was reinvented 8 times since Angular one?

The answer to this is No.

This is not the case instead Angular team adheres to the versioning scheme where a new version of Angular is released every six months.

But that new version is not completely rewritten and it does not change everything.

The new version resolves the issue in the previous version and added new features without breaking the existing feature.

Indeed Angular 12 is the same as Angular 2. When we see syntax and philosophy then most of the things are the same.

In simple words, if you know Angular 2 then there is no difficulty in learning Angular 8 or 9, or 12.

Also, you found that there is no big change in syntax, and the syntax is almost the same as in previous versions.

Overall it is the same framework and some minor changes were added to this. So, among the different Angular versions, we have small incremental changes that are backward compatible.


Conclusion:

In the comparison of the Angular versions, we have learned about their breaking changes, performance & the changes in the core structure, and various other deprecations and upgrades. Angular 13 release was within a few months after the release of Angular 12. However, looks like we can expect the next stable version by end of the year.

Angular v11Angular v12
Typescript 4.0Typescript 4.2
Webpack 5 SupportWebpack 5.37 Support
Migration to ESLintMigrating from legacy i18n message IDs
Deprecation of IE 9, 10, and IE mobile.Deprecating support for IE11.
Updates on Operation Blog.
Improved component tests harness.
Updated Language Service Preview.
HTTP improvements.
strict checks with a flag.Default strict mode
Roadmap to provide early feedbackRoadmap to inform about the priorities of the Angular team
Updated Language Service PreviewMigration to default IVY-based language service
New Default Browser ConfigurationUpdated Language Service Preview
Improved Ngcc compilerImproved logging and reporting

Azure Blob storage trigger for Azure Functions - Messag from Azure Blob Storage to Azure-Service-Bus using azure blob trigger funtion

Azure Function

Azure Functions is a serverless computing service and is hosted on the Microsoft Azure public cloud. It is designed to accelerate and simplify application development. 

Azure Functions are the individual functions created in a Function App. Every Function can be invoked using the configured trigger.


 Blob Storage working scenario.

The Blob storage trigger starts a function when a new or updated blob is detected. The blob contents are provided as input to the function.

When Azure Function runs, it needs to know how to connect to the blob container. In local.settings.json from the Storage Account copy the connection string from Access keys and add the connection string in local.settings.json 

 Blob Trigger function having parameter myBlob which gives the details of the uploaded blob,

These details will send to Service Bus Queue for further process.

  


Azure Function Will be Triggered once the file is uploaded to Azure Storage Account





Prerequisites

  • Microsoft Azure Account.
  • Visual Studio with the Azure Development workload enabled. you can also create Azure Function directly in the portal, but the visual studio is preferred when you want easy source control integration.


Code Snippet for Azure Blob Trigger Function

Function Name: Triggerwhenfileuploads
Return Type: JSON
Blob Container Name: Your-container-Name
Service bus Queue Name: Your-Queue-Name
 

BlobTrigger

name - holds the name of the file found in the blob container.

myBlob - holds the content of the file.

containerName - actual container name created in blob storage.

connection - blob storage connection string.

Service Bus

Service-Bus-demo: Service bus Queue Name

Connection - Service bus connection string.







Class File For Message     






OutPut






The connection string from the storage account to local.setting.json

This config file will not be going to deploy to Azure, so will need to specify the information in the portal as well.