DEV TEST - Full stack Bootstrap and ASP.NET MVC - Testing

news/2026/1/17 19:02:20/文章来源:https://www.cnblogs.com/Mattcoder/p/9222108.html

,General topic : https://www.cnblogs.com/Mattcoder/p/8878481.html

Unit Test

Integration Test - NetCore

 

 

Integration Test - Net4.5 

Unit Test at all layers

Add FluentAssertions and NUnit

 test-test the layered class, 

from controller (test the action result base on conditions)

to sevice

to repo

Focus is on verify whether the filtering behavior on the EF is correctly returnning desired entities

Fill the DBSet with test data that simulate the data populated from DB

namespace Wrox.BooksRead.Web.Tests.Repository
{public static class DbSetExtension{public static void SetDataSource<T>(this Mock<DbSet<T>> mockSet, IList<T> source) where T : class{var data = source.AsQueryable();mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(data.Provider);mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(data.Expression);mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(data.ElementType);mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());}}
}

Second example

 

namespace XOProject.Tests
{internal static class DbSetExtension{public static void MockDbSet<T>(this Mock<DbSet<T>> mockSet, IEnumerable<T> source) where T:class{var list = source.AsQueryable();mockSet.As<IAsyncEnumerable<T>>().Setup(m => m.GetEnumerator()).Returns(new TestUseAsyncEnumerator<T>(list.GetEnumerator()));mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(new TestUseAsyncQueryProvider<T>(list.Provider));mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(list.Expression);mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(list.ElementType);mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(list.GetEnumerator());}}}
using Microsoft.EntityFrameworkCore.Query.Internal;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;namespace XOProject.Tests
{/// <summary>/// The type is to mock IAsyncQueryProvider which is rquired in IQuerable async methods/// </summary>/// <typeparam name="TEntity"></typeparam>internal class TestUseAsyncQueryProvider<TEntity> : IAsyncQueryProvider{private readonly IQueryProvider _inner;internal TestUseAsyncQueryProvider(IQueryProvider inner){_inner = inner;}public IQueryable CreateQuery(Expression expression){return new TestUseAsyncEnumerable<TEntity>(expression);}public IQueryable<TElement> CreateQuery<TElement>(Expression expression){return new TestUseAsyncEnumerable<TElement>(expression);}public object Execute(Expression expression){return _inner.Execute(expression);}public TResult Execute<TResult>(Expression expression){return _inner.Execute<TResult>(expression);}public IAsyncEnumerable<TResult> ExecuteAsync<TResult>(Expression expression){return new TestUseAsyncEnumerable<TResult>(expression);}public Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken){return Task.FromResult(Execute<TResult>(expression));}}internal class TestUseAsyncEnumerable<T> : EnumerableQuery<T>, IAsyncEnumerable<T>, IQueryable<T>{public TestUseAsyncEnumerable(IEnumerable<T> enumerable): base(enumerable){ }public TestUseAsyncEnumerable(Expression expression): base(expression){ }public IAsyncEnumerator<T> GetEnumerator(){return new TestUseAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());}IQueryProvider IQueryable.Provider{get { return new TestUseAsyncQueryProvider<T>(this); }}}internal class TestUseAsyncEnumerator<T> : IAsyncEnumerator<T>{private readonly IEnumerator<T> _inner;public TestUseAsyncEnumerator(IEnumerator<T> inner){_inner = inner;}public void Dispose(){_inner.Dispose();}public T Current{get{return _inner.Current;}}public Task<bool> MoveNext(CancellationToken cancellationToken){return Task.FromResult(_inner.MoveNext());}}}
AsyncEnumerator

 

 

 

 [Test]public async Task UpdateLatestPrice_ShouldUpdateMostRecentPrice(){// Arrangevar hourRates = new List<HourlyShareRate>() {new HourlyShareRate {Symbol = "CBI",Rate = 330.0M,TimeStamp = new DateTime(2019, 08, 17, 5, 0, 0)},new HourlyShareRate {Symbol = "CBI",Rate = 130.0M,TimeStamp = new DateTime(2020, 08, 17, 5, 0, 0)},new HourlyShareRate {Symbol = "CBI",Rate = 430.0M,TimeStamp = new DateTime(2018, 08, 17, 5, 0, 0)}};var mockSet = new Mock<DbSet<HourlyShareRate>>();mockSet.MockDbSet<HourlyShareRate>(hourRates);HourlyShareRate share = null;var mockContext = new Mock<ExchangeContext>();var mockRepository = new Mock<ShareRepository>(mockContext.Object);var shareController = new ShareController(mockRepository.Object);mockContext.Setup(i => i.Set<HourlyShareRate>()).Returns(mockSet.Object);mockRepository.Setup(i => i.UpdateAsync(It.IsAny<HourlyShareRate>())).Returns(Task.FromResult<object>(null)).Callback<HourlyShareRate>((p) => { share = p; });// Act
shareController.UpdateLastPrice("CBI");// AssertAssert.AreEqual(new DateTime(2020, 08, 17, 5, 0, 0), share.TimeStamp);Assert.AreEqual(10.0M, share.Rate);}
Test Code

 

Use Nnuit to assert exception throwed.

 

 

Integration Test

.NET CORE

Add reference to 

 

.NET 4.5 

Integration Test is expensive, this will focus on a happy path end to end from controller to repo to DB and finally verfiy the data bind to the view

[TestMethod][TestCategory("Integration Test")]public void GetAllAction_WhenCall_ShouldReturnProductInFutureOnlyToView(){//ArranageProduct[] products = new[]{ new Product { Id = 100, CreateDate = DateTime.Now.AddDays(1), Name = "Dummy1", Category = 0, Price = 0 } ,new Product { Id = 101, CreateDate = DateTime.Now.AddDays(2), Name = "Dummy2", Category = 0, Price = 0 },new Product { Id = 102, CreateDate = DateTime.Now.AddDays(-2), Name = "DummyObsolete", Category = 0, Price = 0 } };Category category = new Category { Id = 0, Name = "Dummy Category" };try{context.Categories.Add(category);context.Products.AddRange(products);context.SaveChanges();//Act DummyController controller = new DummyController(new UnitOfWork());var result = controller.GetAllAction();//Assertvar resultProducts = result.ViewData.Model as List<Wrox.BooksRead.Web.Models.Product>;resultProducts.Should().HaveCount(2);}finally{//Tear Down
                context.Products.RemoveRange(products);context.Categories.Remove(category);context.SaveChanges();}}

 Add nuit to better support transcaction scope , to make nunit test visible on test explorer, we need to add nunit 2 test adpater at tool->extension and updates

Add an attribute class that inherit ITestAction which is AOP design to insert an action before and after test execution

public class Isolated : Attribute, ITestAction{private TransactionScope transcope;public ActionTargets Targets{get {   return ActionTargets.Test;}}public void AfterTest(ITest test){transcope.Dispose();}public void BeforeTest(ITest test){transcope = new TransactionScope();}}

Apply the attribution to integration test that leveage DB transaction

 [Test, Isolated][Category("Integration Test")]public void GetUserNotification_WhenCall_ShouldReturnCorrectCountOfNotification(){//ArranageProduct[] products = new[] { new Product { Id = 100, CreateDate = DateTime.Now.AddDays(1), Name = "Dummy1", Category = 0, Price = 0 } };//, new Product { Id = 101, CreateDate = DateTime.Now.AddDays(2), Name = "Dummy2", Category = 0, Price = 0 },//    new Product { Id = 102, CreateDate = DateTime.Now.AddDays(-2), Name = "DummyObsolete", Category = 0, Price = 0 } };var productNotification = new ProductNotification{Id = 1,Product = products[0],Notification = string.Format(Utility.PRODUCT_PRICE_CHANGE_NOTIFICATION,new object[] {products[0].Id,products[0].Name,products[0].Price.ToString(),2}) };productNotification.UserProductNotifications.Add(new UserProductNotification { Id = 1, UserId = "1234", IsRead = 0, ProductNotificationId = 1 });var user = new AspNetUser(){Id = "1234",Name = "mockuser",UserName = "matt",EmailConfirmed = true,LockoutEnabled = true,PhoneNumberConfirmed = true,TwoFactorEnabled = true,AccessFailedCount = 0,};Category category = new Category { Id = 0, Name = "Dummy Category" };try{context.AspNetUsers.Add(user);context.Categories.Add(category);context.Products.AddRange(products);context.ProductNotifications.Add(productNotification);context.SaveChanges();//Act UserNotificationController controller = new UserNotificationController(new UnitOfWork());var result = controller.GetUserNotification("1234");//Assertresult.Should().HaveCount(1);}catch (Exception ex){System.Diagnostics.Debug.Write(ex.Message);}finally{              }}

 

and domain class.each 

class can have a dedicated test class.

use the method wirh naming convention of Method_Condition_Result.each methos

shud be aroind 5-10 lins of code and only one aseestion.

repo test requires Mock(DbSetl) object, mainly to test filtered condition really effective.

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/1174496.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

DEV TEST - Full stack Bootstrap and ASP.NET MVC - Testing

DEV TEST - Full stack Bootstrap and ASP.NET MVC - Testing,General topic : https://www.cnblogs.com/Mattcoder/p/8878481.html Unit Test Integration Test - NetCoreIntegration Test - Net4.5 Unit Test at al…

基于深度学习的鸡检测系统(YOLOv10+YOLO数据集+UI界面+Python项目+模型)

一、项目介绍 本研究开发了一种基于YOLOv10的鸡检测和跟踪系统&#xff0c;专注于检测单一类别&#xff1a;rooster&#xff08;鸡&#xff09;。该系统旨在实现对鸡的实时检测和跟踪&#xff0c;适用于养殖场管理、行为研究等场景。YOLOv10作为一种高效的目标检测模型&#xf…

VIRTUALIZATION - Kubernates - Azure Kubernetes Service

VIRTUALIZATION - Kubernates - Azure Kubernetes Service retag the image to make it azure friendly

WEB - AngularJS and Typescript

WEB - AngularJS and TypescriptSource code https://github.com/mattcoder2017/CoreTypescript/tree/master/WebApplication1 AngularIO: https://angular.io/ Nodejs vs angular compatiblity matrix https://angul…

基于深度学习的香蕉成熟度识别检测系统(YOLOv10+YOLO数据集+UI界面+Python项目源码+模型)

一、项目介绍 本文介绍了基于YOLOv10的香蕉成熟度检测系统&#xff0c;旨在通过计算机视觉技术自动识别和分类香蕉的成熟度。该系统能够准确区分六种不同的成熟度类别&#xff1a;新鲜成熟&#xff08;freshripe&#xff09;、新鲜未成熟&#xff08;freshunripe&#xff09;、…

基于深度学习的疲劳驾驶检测系统(YOLOv10+YOLO数据集+UI界面+Python项目+模型)

一、项目介绍 本项目旨在开发一个基于YOLOv10的疲劳检测系统&#xff0c;用于实时检测驾驶员的疲劳状态。系统通过分析驾驶员的面部表情&#xff0c;特别是眼睛和嘴巴的状态&#xff0c;来判断其是否处于疲劳状态。模型共分为四类&#xff1a;打哈欠&#xff08;Yawn&#xff0…

强烈安利!自考必看TOP8一键生成论文工具测评

强烈安利&#xff01;自考必看TOP8一键生成论文工具测评 2026年自考论文工具测评&#xff1a;为何需要一份权威榜单&#xff1f; 随着自考人数逐年增加&#xff0c;论文写作成为众多考生必须面对的难题。从选题构思到文献整理&#xff0c;再到格式规范和内容润色&#xff0c;每…

基于深度学习的生菜周期检测系统(YOLOv10+YOLO数据集+UI界面+Python+模型)

一、项目介绍 YOLOv10生菜生长周期检测系统 是一个基于YOLOv10&#xff08;You Only Look Once version 10&#xff09;目标检测算法的智能系统&#xff0c;专门用于检测和分类生菜在不同生长阶段的生长状态。该系统能够自动识别生菜的生长周期&#xff0c;并将其分类为五个不…

西门子200Smart加Smart 1000 IE水处理程序画面案例。 采用成熟、可靠、先进、...

西门子200Smart加Smart 1000 IE水处理程序画面案例。 采用成熟、可靠、先进、自动化程度高的反渗透精混床除盐水处理工艺&#xff0c;确保处理后的超纯水水质确保处理后出水电阻率达到18.2MΩ.cm, 高纯水制取设备关键设备及耗材采用国际主流先进可靠产品&#xff0c;采用PLC触摸…

震惊!这家浙江头部AI科技公司,竟然藏着这样的秘密!

震惊&#xff01;这家浙江头部AI科技公司&#xff0c;竟然藏着这样的秘密&#xff01;当前行业内对AI技术的认知多聚焦于技术迭代&#xff0c;却鲜少关注落地环节的“适配成本”问题。尤其在中小微企业中&#xff0c;这一痛点尤为突出。许多企业在推进AI转型时&#xff0c;常常…

计算机毕业设计 java 疫苗预约系统 基于 Java 的智能疫苗接种预约管理平台 Java 疫苗接种全流程管理系统

计算机毕业设计 java 疫苗预约系统 9&#xff08;配套有源码 程序 mysql 数据库 论文&#xff09;本套源码可以先看具体功能演示视频领取&#xff0c;文末有联 xi 可分享随着网络科技的飞速发展和人们健康意识的提升&#xff0c;疫苗预约需求日益增长&#xff0c;传统线下预约模…

PERFORMANCE TEST - WebPerf Test

PERFORMANCE TEST - WebPerf TestNo web browser Organize your test early on -could be base on user stories Small granularity so you know what is slowAdding Validatation Rule All have LEVEL to indicate im…

震惊!浙江这家头部AI公司光景泽创,究竟藏着啥秘密?

震惊&#xff01;浙江这家头部AI公司光景泽创&#xff0c;究竟藏着啥秘密&#xff1f;当多数AI企业还在卷技术参数时&#xff0c;浙江光景泽创科技公司&#xff08;以下简称“光景泽创”&#xff09;却用一组数据刺痛了行业神经&#xff1a;服务企业超500家&#xff0c;帮助广州…

震惊!浙江这家AI科技头部公司光景泽创,究竟有何过人之处?

跨境生意的“效率革命”&#xff1a;解码光景泽创的AI破局之道当前跨境电商行业正陷入一场“效率焦虑”——多语言素材人工翻译成本高、海外直播时区适配难、客户咨询响应慢导致流失率超30%&#xff0c;这些隐性痛点正在吞噬企业的利润空间。浙江光景泽创科技有限公司&#xff…

Dev Mentor - RabbitMq

Dev Mentor - RabbitMqBus is to be used to inform or broadcast the mutated state and command that need to be processed by multiple servicesScenario 1 ProductService received rest post message to persist…

PyTorch 自动微分:超越 `backward()` 的动态图深度探索

PyTorch 自动微分&#xff1a;超越 backward() 的动态图深度探索 引言&#xff1a;自动微分的范式之争 在深度学习的工程实践中&#xff0c;自动微分&#xff08;Automatic Differentiation, AD&#xff09;已成为模型训练的基石。与符号微分和数值微分不同&#xff0c;自动微分…

计算机毕业设计 java 疫情物资管理系统 Java 疫情物资智能管理与调配平台 基于 Spring Boot 的疫情物资申请捐赠系统

计算机毕业设计 java 疫情物资管理系统 v5rne9&#xff08;配套有源码 程序 mysql 数据库 论文&#xff09;本套源码可以先看具体功能演示视频领取&#xff0c;文末有联 xi 可分享在疫情防控常态化背景下&#xff0c;疫情物资的高效管理、精准调配与供需对接成为关键需求&#…

震惊!浙江这家AI科技公司,竟是光景泽创!

浙江光景泽创科技&#xff1a;AI 企服领域的创新引领者在当今数字化浪潮汹涌的时代&#xff0c;AI 技术在企业服务领域的应用正成为行业发展的关键驱动力。然而&#xff0c;企业在引入 AI 服务时&#xff0c;往往面临着诸多挑战。从行业实操反馈来看&#xff0c;许多企业在 AI …

Dev Mentor - Seq Serilog

Dev Mentor - Seq Serilog {"app": {"name": "order-service"},"elk": {"enabled": false,"url": "http://10.89.24.148:9200","indexFo…

基于深度学习的棉花分类检测系统(YOLOv8+YOLO数据集+UI界面+Python项目+模型)

一、项目介绍 摘要 本项目基于YOLOv8深度学习目标检测算法&#xff0c;开发了一套高效、精准的棉花品种智能分类检测系统。该系统能够自动识别并分类四种主要棉花品种&#xff1a;亚洲棉&#xff08;G. arboreum&#xff09;、海岛棉&#xff08;G. barbadense&#xff09;、…