集成测试——Spring TestContext框架支持详细解说

Spring 框架文档5.3.9 5.3.9 本章涵盖 Spring 对集成测试的支持和单元测试的最佳实践。Spring 团队提倡测试驱动开发(TDD)。Spring 团队发现正确使用控制反转 (IoC) 确实使单元和集成测试更容易(因为 setter 方法和类上适当的构造函数的存在使它们更容易在测试中连接在一起,而不必设置服务定位器注册表和类似结构)。 一、Spring测试介绍 测试是企业软件开发的一个组成部分。本章重点介绍 IoC 原则为单元测试增加的价值以及 Spring Framework 对集成测试的支持 阅读详情

概述

    集成测试是在单元测试之上,通常是将一个或多个已进行过单元测试的组件组合起来完成的,即集成测试中一般不会出现Mock对象,都是实实在在的真实实现。

    对于单元测试,如前边在进行数据访问层单元测试时,通过Mock HibernateTemplate对象然后将其注入到相应的DAO实现,此时单元测试只测试某层的某个功能是否正确,对其他层如何提供服务采用Mock方式提供。

    对于集成测试,如要进行数据访问层集成测试时,需要实实在在的HibernateTemplate对象然后将其注入到相应的DAO实现,此时集成测试将不仅测试该层功能是否正确,还将测试服务提供者提供的服务是否正确执行。

    使用Spring的一个好处是能非常简单的进行集成测试,无需依赖web服务器或应用服务器即可完成测试。Spring通过提供一套TestContext框架来简化集成测试,使用TestContext测试框架能获得许多好处,如Spring IoC容器缓存、事务管理、依赖注入、Spring测试支持类等等。

Spring TestContext框架支持

Spring TestContext框架提供了一些通用的集成测试支持,主要提供如下支持:

一、上下文管理及缓存:

    对于每一个测试用例(测试类)应该只有一个上下文,而不是每个测试方法都创建新的上下文,这样有助于减少启动容器的开销,提供测试效率。可通过如下方式指定要加载的上下文:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
    locations={"classpath:applicationContext-resources-test.xml",
               "classpath:cn/javass/point/dao/applicationContext-hibernate.xml"})
public class GoodsHibernateDaoIntegrationTest {
}
  • locations:指定Spring配置文件位置;

  • inheritLocations:如果设置为false,将屏蔽掉父类中使用该注解指定的配置文件位置,默认为true表示继承父类中使用该注解指定的配置文件位置。

二、Test Fixture(测试固件)的依赖注入:

Test Fixture可以指运行测试时需要的任何东西,一般通过@Before定义的初始化Fixture方法准备这些资源,而通过@After定义的销毁Fixture方法销毁或还原这些资源。

Test Fixture的依赖注入就是使用Spring IoC容器的注入功能准备和销毁这些资源。可通过如下方式注入Test Fixture:

@Autowired
private IGoodsDao goodsDao;
@Autowired
private ApplicationContext ctx;

即可以通过Spring提供的注解实现Bean的依赖注入来完成Test Fixture的依赖注入。

三、事务管理: 

开启测试类的事务管理支持,即使用Spring 容器的事务管理功能,从而可以独立于应用服务器完成事务相关功能的测试。为了使测试中的事务管理起作用需要通过如下方式开启测试类事务的支持:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
    locations={"classpath:applicationContext-resources-test.xml",
             "classpath:cn/javass/point/dao/applicationContext-hibernate.xml"})
@TransactionConfiguration(
transactionManager = "txManager", defaultRollback=true)
public class GoodsHibernateDaoIntegrationTest {
}

Spring提供如下事务相关注解来支持事务管理:

  • @Transactional:使用@Transactional注解的类或方法将得到事务支持 

  • transactionManager:指定事务管理器;

  • defaultRollback:是否回滚事务,默认为true表示回滚事务。

Spring还通过提供如下注解来简化事务测试:

  • @Transactional:使用@Transactional注解的类或方法表示需要事务支持;

  • @NotTransactional:只能注解方法,使用@NotTransactional注解的方法表示不需要事务支持,即不运行在事务中,Spring 3开始已不推荐使用;

  • @BeforeTransaction和@AfterTransaction:使用这两个注解注解的方法定义了在一个事务性测试方法之前或之后执行的行为,且被注解的方法将运行在该事务性方法的事务之外。

  • @Rollback(true):默认为true,用于替换@TransactionConfiguration中定义的defaultRollback指定的回滚行为。

四、常用注解支持:Spring框架提供如下注解来简化集成测试:

  • @DirtiesContext:表示每个测试方法执行完毕需关闭当前上下文并重建一个全新的上下文,即不缓存上下文。可应用到类或方法级别,但在JUnit 3.8中只能应用到方法级别。

  • @ExpectedException:表示被注解的方法预期将抛出一个异常,使用如@ExpectedException(NotCodeException.class)来指定异常,定义方式类似于Junit 4中的@Test(expected = NotCodeException.class),@ExpectedException注解和@Test(expected =……)应该两者选一。

  • @Repeat :表示被注解的方法应被重复执行多少次,使用如@Repeat(2)方式指定。

  • @Timed:表示被注解的方法必须在多长时间内运行完毕,超时将抛出异常,使用如@Timed(millis=10)方式指定,单位为毫秒。注意此处指定的时间是如下方法执行时间之和:测试方法执行时间(或者任何测试方法重复执行时间之和)、@Before和@After注解的测试方法之前和之后执行的方法执行时间。而Junit 4中的@Test(timeout=2)指定的超时时间只是测试方法执行时间,不包括任何重复等。

五、TestContext框架支持类:提供对测试框架的支持,如Junit、TestNG测试框架,用于集成Spring TestContext和测试框架来简化测试,TestContext框架提供如下支持类:

    Spring 中文解析核心篇-集成测试之TestContext 单元测试 TestContext 是Spring提供的一个关键工具,用于简化和增强单元测试的编写和执行过程。TestContext 是Spring框架中集成测试的重要组成部分,它提供了一套强大而灵活的工具,简化了单元测试的编写和执行过程。使用TestContext,我们可以方便地加载Spring配置文件、管理Bean的生命周期、注入依赖项,并执行各种测试操作,例如模拟对象和验证行为。TestContext 是Spring框架的一部分,旨在提供一个统一的环境,用于执行基于Spring的单元测试。 阅读详情

    相关推荐

    Spring集成测试全面实战指南

    简介:在Spring框架中,集成测试是验证各组件协同工作的关键步骤。Spring提供了强大的测试支持,包括Spring Test Framework、测试配置、数据源管理、Mocking机制及多种专用测试注解,如@WebMvcTest、@DataJpaTest和@SpringBootTest。本指南系统介绍了如何利用这些工具高效开展集成测试,涵盖事务管理、REST API测试、测试监听器等核心内容,帮助开发者构建稳定可靠的Spring应用。

    weixin_35753291的博客 859

    Endnote 导入参考文献的时候,格式错误太多了。et.al错误,国标GBT7714在endnote中的详细配置教程,适用于本科,硕士论文文献插入的模板

    EndNote插入文献常遇到以下错误主要如下: 等、et al不分; 英文作者全名大写; 期刊名字使用了缩写(图片里没有体现;卷号、期号缺失时出现乱码,多了半个括号;页码范围略去了相同部分;没有悬挂缩进,本文全部解决,全网最细

    sakura的博客 3万+

    实测338MB/s!FPGA与CYUSB3014的Slave FIFO模式实战避坑(附完整固件与源码)

    本文详细介绍了FPGA与CYUSB3014在Slave FIFO模式下实现338MB/s高速数据传输的实战经验。通过优化硬件设计、固件配置和GPIF II接口设置,解决了USB3.0双向通信中的关键性能瓶颈,并提供了完整的固件与源码参考。

    weixin_30570101的博客 458

    Windows系统的Mamba环境配置详细教程(状态空间模型)

    causal_conv1d也是安装mamba的依赖必须库。安装完成后,通过pip list可以查看到安装的库。Triton是安装mamba的依赖,需要先安装。上述工作准备好后,按下面步骤安装。直接根据离线文件安装即可。是自己的虚拟环境名字。

    2301_77831163的博客 3677

    DIY天文摄影:如何用NMP溶剂安全去除佳能CMOS传感器的拜耳滤镜(附详细步骤)

    本文为天文摄影爱好者提供了一份详尽的DIY指南,介绍如何使用NMP溶剂安全去除佳能CMOS传感器的拜耳滤镜,将其改造为高灵敏度单色相机。文章深入剖析了NMP溶剂的作用原理与关键风险,并系统性地拆解了从材料准备、分步操作到后期验证的完整实践流程,旨在帮助具备动手能力的爱好者实现深空天体摄影的进阶目标。

    w3x4y的博客 308

    基于Android Studio的校园智能点餐系统开发实战(附完整源码与部署指南)

    本文详细介绍了基于Android Studio开发校园智能点餐系统的完整流程,包括需求分析、环境搭建、数据库设计、客户端与后台功能实现。系统采用SSM框架和MySQL数据库,解决了校园食堂高峰期排队问题,提供高效的点餐体验。附完整源码与部署指南,助力开发者快速构建类似应用。

    weixin_29015801的博客 560

    Vue + ECharts:从零构建智慧农业数据监控大屏(附完整源码)」 「超实用!一步步实现智慧农业大屏,完整代码+讲解」 「前端新手友好:Vue + ECharts 打造炫酷农业数据大屏」 「

    Vue + ECharts:从零构建智慧农业数据监控大屏(附完整源码)」 「超实用!一步步实现智慧农业大屏,完整代码+讲解」 「前端新手友好:Vue + ECharts 打造炫酷农业数据大屏」 「前端可视化项目实战:智慧农业监控大屏开发详解」 「农作物可视化监控:用 Vue 和 ECharts 构建大屏应用」 「从零开始开发一个智慧农业数据大屏(代码+图表展示)」 「前端新手也能实现!智慧农业监控大屏开发教程」 「用 Vue 和 ECharts 搭建动态数据大屏:详细图文教程」 「学习前端大屏开发:

    sky10100100的博客 1535

    Vue+Echarts监控大屏实例四:智慧农业监控模板实例

    本实例通过Vue-Echarts实现了智慧农业监控模板实例界面,学习并使用了vue-echarts的使用,接入高德地图并展示,添加了全屏切换、加载动画小鼓、站点切换及退出等相关功能,提供源码下载。

    Java、前端、小程序学习笔记、问题汇总、项目实例分享,有需要请联系。 7669

    Airtest进阶使用篇-提高脚本稳定性+批量运行脚本

    Airtest进阶篇,主要分享如何提高脚本稳定性+如何批量运行脚本生成测试报告!

    程序员小杨哥的博客 2572

    深度学习工具包 DeepLearningToolbox

    深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

    霍尼韦尔SoftMaster使用说明

    霍尼韦尔SoftMaster使用说明

    TMS_WebGMaps_1.9.8.0_Full_Source

    TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

    C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

    基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

    上一篇: 如何测试微信小程序
    下一篇: 一招教你成为大内密探:诊断优化找出消耗CPU性能的内鬼
    TestingGDR
    博客等级 码龄8年 496粉丝 72原创
    评论
    成就一亿技术人!
    拼手气红包6.0元
    还能输入1000个字符
     
     条评论被折叠 查看
    添加红包

    请填写红包祝福语或标题

    个

    红包个数最小为10个

    元

    红包金额最低5元

    当前余额3.43元 前往充值 >
    需支付:10.00元
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付元
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值