Creating database unit test with GitHub Copilot

Step-by-Step Guide Set Up Your Environment: Ensure you have Visual Studio installed. Install the necessary NuGet packages: Moq and xUnit. Create Your Database Mock: Use Moq to create a mock database context. Write Your Unit Test: Define  your test cases using the xUnit framework. Use the mock objects to simulate database interactions. Example Let's say you have a function GetUserById that retrieves a user from the database by their ID.  // UserService.cs using System.Linq; using Microsoft.EntityFrameworkCore;   public class UserService {     private readonly DbContext _context;       public UserService(DbContext context)     {         _context = context;     }       public User GetUserById(int userId)     {         return _context.Set<User>().FirstOrDefault(u => u.Id == userId);     } }   Now, let's create a unit test for this function using a mock database. // UserServiceTests.cs using System.Collections.Generic; using System.Linq; using Moq; using Xunit; using Microsoft.EntityFrameworkCore;   public class UserServiceTests {     [Fact]     public void GetUserById_ReturnsUser()     {         // Arrange         var mockSet = new Mock<DbSet<User>>();         var mockContext = new Mock<DbContext>();         var user = new User { Id = 1, Name = "John Doe" };           var data = new List<User> { user }.AsQueryable();           mockSet.As<IQueryable<User>>().Setup(m => m.Provider).Returns(data.Provider);         mockSet.As<IQueryable<User>>().Setup(m => m.Expression).Returns(data.Expression);         mockSet.As<IQueryable<User>>().Setup(m => m.ElementType).Returns(data.ElementType);         mockSet.As<IQueryable<User>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());           mockContext.Setup(c => c.Set<User>()).Returns(mockSet.Object);           var service = new UserService(mockContext.Object);           // Act         var result = service.GetUserById(1);           // Assert         Assert.Equal(user, result);     } }     Explanation Mocking the Database Context: var mockSet = new Mock<DbSet<User>>(); creates a mock DbSet for the User entity. var mockContext = new Mock<DbContext>(); creates a mock DbContext. Setting Up Mock Behavior: The mockSet is set up to return a predefined list of users when queried. mockContext.Setup(c => c.Set<User>()).Returns(mockSet.Object); ensures that the DbContext returns the mock DbSet. Writing the Test: The GetUserById_ReturnsUser test method arranges the mock objects, acts by calling the GetUserById method, and asserts that the returned user matches the expected user. Using GitHub Copilot, you can generate similar unit tests by providing clear prompts and leveraging its code suggestions to streamline the process. 

Is Object Oriented Still Applicable?

Cloud era do We need OO? This is q good question. We have a lot scripting framework that can be used to develop sophisticated web. We have low level codes that can help build an app within a minute. We have cloud template to deploy solution in minutes. Do we still need Object Oriented (OO)? The answer is it depends. When you build a game, you might need OO. In example, unity project needs C# scripting with OO. When you build a website, you might need OO. In example, asp.net need C# with the MVC (Model View Control) When you build a mobile app, you might need OO. In example, building Xamarin codes. When you build a desktop app, you might need OO. In example, building Windows Form or WPF codes. So the most answer is YES. Learning OO in the cloud era So we back in the square one. What we need to learn in OO especially in the cloud era. Setup the tools and basic language of C#. We can start to learn OO by setup the SDK, IDE, and many more. Configuring Visual Studio Configuring Visual Studio Codes Understanding Class, Namespace, and Variables Understanding Method, Parameter, and Library Understanding Building Process in Visual Studio Introducing UML class diagram Abstraction. We discuss the abstraction implementation. Abstraction concept Abstraction C# example Inheritance. The inheritance pillar that helps to make a class reusable Inheritance concept Inheritance C# example Interface. The interface pillar that helps to make a class consistent Interface concept Interface C# example Polymorphism. The pillar that helps to make a class extendable and less changes Polymorphism concept Polymorphism C# example Object oriented analysis and design (OOAD) Introduction OOAD OOAD in example A Pie. Putting it all together. Creating a full project in Visual Studio consoles project Case Study project: Class Design Case study project: relationship Design Case study project: test design Design patterns. Providing the information about how to create a software with the best design in mind. Creational pattern examples Structural pattern examples Behavioural pattern examples Refactoring in Visual Studio SOLID principles. Providing the information to make OO programming more approachable and consistent Single responsibility principle Open/Closed principle Liskov Substitution Principle Interface Segregation Principle (ISP) Dependency Inversion Principle Object oriented in Database Layer Database API model: ADO.NET Database ORM Model: Entity Framework Project Creating Database Layer Object-oriented in-Service Layer Web services, JSON and HTTP REST Project Creating Service Layer Object oriented in Desktop App Introducing WPF, Windows Form, and UWP Project Creating Desktop App. Object Oriented in web App Introducing MVC Project Creating Web App Object Oriented in Mobile App Introducing Xamarin and MAUI Project creating Mobile App Starting 1 – 9, you can work with any sample or spike codes that shows the concept. In Chapter 10 – 14 you can build a multi-channel application that build the software from end to end. //

Video Game Development in .NET Framework

Video game development in Visual Studio Microsoft loves video games. Xbox, Game Pass, and DirectX is a real proof that Microsoft is committed to video game. As a result, we see a lot opportunity to build video game in any platform with Microsoft Based technology. You can see a specific section namely gaming. Microsoft has two categories: Game Development with Unity (C#) and Game Development with C++. It means you can build a video game with managed codes or native C++ codes. Microsoft provides support for Unity (2D/3D), DirectX (2D/3D), Unreal 3D, and Cocos2D. it's more than enough for developing a game. Additional Video Game Development tools If you feel you need more video game development tools you can visit these links MonoGame. It's a successor of XNA Framework. MonoGame provides multi-platform development for video game. You can visit Getting Started | MonoGame Documentation to learn more about MonoGame. What I love from MonoGame is well integrated with Visual Studio. However, it basically collection of library so you need to do extra effort to build game and contents. GoDot. It's a new game engine. GoDot provides project manager and editor for game development. You can learn more here Godot Docs – 3.3 branch — Godot Engine (stable) documentation in English WaveEngine. It's a professional game engine and animation based on .NET 5. You can develop AR and MR video games with WaveEngine. You can see some demos here GitHub - WaveEngine/Samples: This repository contains all the official samples of WaveEngine. Stride. It is awesome game engine with support for multi deployment and C# 8.0 supports. You can learn more at Stride documentation | Stride (stride3d.net) FlatRedBall. It a good game engine for building 2D videos games. You can learn more about Tutorials – FlatRedBall   medianet_width = "600"; medianet_height = "250"; medianet_crid = "858385152"; medianet_versionId = "3111299";

Consuming Rest API in an Easy Way

Background There are numerous ways to consume REST API in C#. Starting with HttpClient, WebClient, HTTPWebRequest and Third-Party API. On this post, I will show you how to consume REST API in an easy way with C#. Requirements For this lab we use: Visual Studio 2019 – http://visualstudio.com Newton soft JSON - https://www.newtonsoft.com/json/ Rest sharp - http://restsharp.org/ Horoscope REST API sample – http://sandipbgt.com/theastrologer/api/horoscope // Let's get started #1 Creating a project with Visual Studio 2019 we created two projects the first one is Class Library and the second one is Console App. It used .NET Framework 4.7.2. we downloaded two Nuget package: Newtonsoft JSON and RestSharp for the Class Library project #2 Composing Classes for our REST objects The REST API will be consumed as an object. Therefore, we created several classes and enumeration #3 Creating Class that Consumes the REST API We created a class that has a method to consume REST API. We deserialize the REST API as shown below. We read the content and save the result into Zodiacresult Class. Please note we use DeserializeObject (from newtonsoft) and RestClient (from restsharp). #4 Creating Class that Display the REST API We created a console app that consume the library. The REST API has a nested result. Therefore, the Zodiacresult contains an array namely Meta object. We consume the Meta object and accessing through their properties. #5 Testing the result Lets push the F5 button and you can see, we can consume the rest API easily in dotnet. Have a question? Just put it in the comments. Enjoy your weekend. //

Topics Highlights

About @ridife

This blog will be dedicated to integrate a knowledge between academic and industry need in the Software Engineering, DevOps, Cloud Computing and Microsoft 365 platform. Enjoy this blog and let's get in touch in any social media.

Xbox

Month List

Visitor