- DataGridView列表筛选
幽兰的天空
前端技术C#编程前端
以下是实现DataGridView列表筛选的解决方案:解决思路创建一个TextBox控件,用户可以在其中输入筛选条件。为TextBox的TextChanged事件添加处理程序,当用户输入文本时,根据输入的文本对DataGridView中的数据进行筛选。使用DataView作为BindingSource的数据源,通过设置DataView的RowFilter属性实现筛选功能。实现代码usingSyst
- 数据分析思维
幽兰的天空
combobox数据仓库大数据
了解数据分析的本质是什么在数据中寻找解决问题的方法。使用大量的数据、统计分析、定量、定性分析和预测模型及基于事实的管理来推动决策过程和实现价值增生。数据分析思维1.一个思维模型:目标导向分析法2.做好分析准备:探索性数据分析数据分析的四个层级1.描述性分析2.诊断性分析3.预测性分析4.决策性分析
- 51hook 课程之inline hook代码
不要影响我叠Q
逆向工程安全
#include"main.h"//1、找到要HOOK的函数//2、保存要hook的函数的前5个字节//3、计算目标函数距离jump指令的下一条指令的偏移offset//4、改变函数的前5个字节改成jmpoffset(即0xE9offset)//1、进行hook的初始工作,找到hook函数的地址并保存函数的前5个字节计算出偏移值保存改变后的前5个字节//2、安装钩子//3、卸载钩子//4、自定义函
- Python数据分析常见面试题和答案01-10
飞翔还哈哈6
Python数据分析pythonpandas数据分析
以下是一些Python数据分析常见面试题和答案:1.Python中的list和tuple的区别是什么?答:List是可变的,而元组(tuple)是不可变的。因此,使用list来存储需要频繁修改的数据,而使用元组来存储不能更改的数据项。2.解释NumPy中的数组?为什么numpy在数据分析中很重要?答:NumPy是Python中提供高性能科学计算和数据分析的包。NumPy数组是一种类似于列表的数据结
- leetCode热门100题——1.两数之和
Bin二叉
算法数据结构leetcode
题目描述给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素(但原数组中可能有两个相同的元素,这种情况可以使用)。你可以按任意顺序返回答案。示例1:输入:nums=[2,7,11,15],target=9输出:[0,1]解释:因为nums[0]+nums[1
- ORACLE与SQL SERVER的区别
nanzhuhe
文章笔记数据库Oracle
ORACLE与SQLSERVER的区别转载自:https://www.cnblogs.com/chuncn/archive/2009/01/28/1381262.html体系结构ORACLE的文件体系结构为:数据文件.DBF(真实数据)日志文件.RDO控制文件.CTL参数文件.ORASQLSERVER的文件体系结构为:.MDF(数据字典).NDF(数据文件).LDF(日志文件)ORACLE存储结构
- kafka+connector集群迁移
mark.meng
中间件kafka分布式
示例环境ip部署信息备注192.168.181.121zookeeper、kafka、connecter待迁移集群节点1192.168.181.14zookeeper、kafka、connecter待迁移集群节点2192.168.181.49zookeeper、kafka、connecter待迁移集群节点3192.168.181.61zookeeper、kafka、connecter新集群节点11
- keepalived+haproxy实现高可用集群
mark.meng
中间件运维
实验环境172.16.32.21172.16.32.22Vip:172.16.32.301.部署httpd测试服务yuminstallhttpdecho"172.16.32.22">>/var/www/html/id.htmlsystemctlstarthttpdcurl172.16.32.22/id.html172.16.32.222.部署haproxy实现负载均衡yuminstallhapro
- MySQL—多表查询—自连接
岁岁岁平安
MySQL自学mysql数据库DataGripMySQL多表查询自连接
一、引言自连接,顾名思义就是自己连接自己。自连接的语法结构:表A别名Ajoin表A别名BON条件...;注意:1、这种语法有一个关键字:join2、自连接查询可以是内连接的语法,可以是外连接的语法(当然包括左外连接和右外连接)接下来去工具DataGrip通过两个需求去演示一下自连接查询的语法。二、实操(0)两张表的结构以及数据展示员工表emp部门表dept(1)查询员工及其所属领导的名字1、分析在
- 3.6.树状数组
赵鑫亿
c++数据结构与算法c++算法开发语言数据结构
树状数组基本原理树状数组(BinaryIndexedTree,简称BIT)是一种高效的数据结构,它可以在O(logn)的时间复杂度下实现对数组的单点更新和区间求和操作。前置知识lowbit(intx)函数:计算x的最低位的1及其后面的0组成的数,例如lowbit(6)(二进制为110)等于2(二进制为10)。在树状数组中,i元素的右父节点为i+lowbit(i),左父节点为i-lowbit(i)核
- PCL点云处理算法汇总(C++长期更新低价精品版)
点云侠'
点云学习算法c++开发语言计算机视觉
可笑,我当然知道是抄袭的啊,还用你提醒?要不是你们审核不作为,我能抄这么明目张胆???目录一、点云滤波1、常用滤波器2、采样滤波3、裁剪滤波二、KD树与八叉树1、KD树2、八叉树三、点云配准粗配准精配准对应关系配准精度坐标转换刚体运动变换四、点云拟合分割1、RANSAC2、其他几何分割五、三维重建六、特征点与特征描述1、点云的属性2、关键点提取3、特征描述子七、基础函数1、common模块2、其他
- Spring 框架中的 Bean 生命周期全解析
码农小灰
面试题Springjavajavaspringservlet
目录一、Bean生命周期的关键步骤二、使用场景说明在当今的软件开发领域,Spring框架凭借其强大的依赖注入和控制反转特性,已成为Java开发中不可或缺的一部分。而Spring框架的核心组件之一——Bean,其生命周期的管理对于应用程序的稳定运行和资源的有效利用至关重要。本文将深入探讨Spring框架中Bean的生命周期,从实例化到销毁的每一个关键步骤,并结合使用场景进行说明,帮助开发者更好地理解
- ElasticSearch11-8.x 新特性
李宥小哥
常用中间件中间件
零、文章目录ElasticSearch11-8.x新特性1、API变更(1)类型(_type)移除在Elasticsearch8.x中,索引中的_type已经被完全移除。这意味着所有文档在同一个索引中将不再区分类型,简化了索引结构,但同时也要求开发者调整应用程序逻辑以适应这一变化。(2)客户端库更新Elasticsearch8.x不再支持rest-high-level-client,而是推荐使用新
- 【2017-2025】Adobe Premiere Pro(简称PR)专业视频编辑软件下载
iNBySNG
adobe音视频
AdobePremierePro软件简介AdobePremierePro(简称PR)是由Adobe公司开发的一款专业视频编辑软件,广泛应用于电影制作、电视播出和网络视频的制作。该软件以其强大的编辑功能和灵活的工作流程,在业界中享有盛誉。无论是专业影视制作人还是业余爱好者,PremierePro都能满足他们的需求,为各种视频项目提供卓越的解决方案。下载链接https://pan.baidu.com/
- Python电子书教程汇总
iteye_3941
python
From:http://bathome.net/thread-15554-1-1.html[转载教程]Python电子书教程汇总(2012-02-16更新)简明Python教程(AByteofPython)_1.20_中文版pdfhttp://www.rayfile.com/zh-cn/files/6cdcc561-58b2-11e1-ad5e-0015c55db73d/Python语言从入门到精
- 单例模式
智想天开
单例模式
公众号地址:单例模式更多内容请关注公众号:智想天开1.什么是单例模式?单例模式是一种创建型设计模式,旨在确保一个类在整个应用程序生命周期中只有一个实例,并提供一个全局访问点。通过单例模式,可以避免多个实例带来的资源浪费和数据不一致问题。关键点:唯一性:确保一个类只有一个实例。全局访问:提供一个全局的访问点来获取该实例。2.单例模式的意图控制实例数量:限制类的实例化数量,通常为一个。全局访问点:提供
- 什么是结构体?什么是联合体?结构体和联合体有什么区别?能否在声明过程当中缺省名字?结构体可以包含函数吗?在 C 和 C++ 中有何不同?
SUN_Gyq
c语言c++开发语言
1)结构体结构体(structure)是一种由不同数据类型的成员组成的数据集合类型,它允许将多个相关的变量组合在一起,形成一个更复杂的数据类型。1.找成员当中最大的类型作为对齐2.按照定义的顺序实现空间分配3.实现地址分配要整数倍对齐4.当结构体当中成员为数组时需要将数组拆分成多个该类型的变量5.当结构体当中包含其他结构体类型的结构时先找到它的对齐数从而确定结构体的对齐数再进行分配位域(不存在地址
- 第03讲 原理探究,了解爬虫的基本原理
roc_lpy
Python
转载于拉勾教育-52讲轻松搞定网络爬虫-崔庆才1.爬虫概述我们可以把互联网比作一张大网,而爬虫(即网络爬虫)便是在网上爬行的蜘蛛。如果把网的节点比作一个个网页,爬虫爬到这就相当于访问了该页面,获取了其信息。可以把节点间的连线比作网页与网页之间的链接关系,这样蜘蛛通过一个节点后,可以顺着节点连线继续爬行到达下一个节点,即通过一个网页继续获取后续的网页,这样整个网的节点便可以被蜘蛛全部爬行到,网站的数
- 布隆过滤器
Lin_Miao_09
技术架构哈希算法数据结构算法
目录一、布隆过滤器是什么工作原理优点缺点二、布隆过滤器的使用Guava步骤1:添加依赖步骤2:创建和使用布隆过滤器Redission使用Redisson的RBloomFilter步骤1:添加依赖步骤2:使用RBloomFilter手动使用BitSet实现布隆过滤器示例代码解释使用ReBloom插件实现步骤1:安装Redis和ReBloom模块步骤2:使用ReBloom操作布隆过滤器使用Redis的
- Python网络编程之UDP套接字编程
Ssaty.
udp网络python
第1关:UDP初体验任务描述本关任务:完成一个客户端程序,向服务器端发出请求,传输数据,并设置超时丢包,体验UDP的基本连接过程。相关知识为了完成本关任务,你需要掌握:创建socket对象;发送UDP数据;接收UDP数据;设置超时。创建socket对象创建socket对象是第一步,后续所有的操作都是通过socket对象完成的。创建对象使用socket()函数:s=socket(参数1,参数2)#s
- Python机器学习之XGBoost从入门到实战(基本理论说明)
雪域枫蓝
PythonAtificialIntelligence机器学习python分布式
Xgboost从基础到实战XGBoost:eXtremeGradientBoosting*应用机器学习领域的一个强有力的工具*GradientBootingMachines(GBM)的优化表现,快速有效—深盟分布式机器学习开源平台(DistributedmachinelearningCommunity,DMLC)的分支—DMLC也开源流行的深度学习库mxnet*GBM:Machine:机器学习模型
- VSCode配置调试C-配置launch.json和tasks.json
zhougl996
C与C++笔记
launch.json{//使用IntelliSense了解相关属性。//悬停以查看现有属性的描述。//欲了解更多信息,请访问:https://go.microsoft.com/fwlink/?linkid=830387"version":"0.2.0","configurations":[{"name":"gcc.exe-生成和调试活动文件",//该调试任务的名字,启动调试时会在待选列表中显示"
- 冒泡排序 选择排序 插入排序
2401_89791565
java排序算法算法
packagecom.nobody.sort;/**@authorMr.nobody@Description插入排序@date2020/9/5*/publicclassCode01_InsertionSort{publicstaticvoidinsertionSort(int[]arr){//数组为空,或者数组长度小于2就没必要操作if(null==arr||arr.length=0&&arr[j
- 最长回文字串的多种解法(java)
心 -
java
文章目录1.暴力解法2.中心扩散法3.动态规划法题目要求:给你一个字符串s,找到s中最长的回文子串1.暴力解法列举所有子串;将字符串分解为字符数组char[]arr,方便后续判断是否为回文字符串,接着使用两层for循环去跑字符串s,使用maxf初始化为1去记录最长回文字符串的长度,min记录最长字符串的起始下标。代码如下:publicStringlongestPalindrome(Strings)
- midjourney初学者必看(迅速入门)
会飞the羊
midjourney
Midjourney初步学习:基本操作流程:-新建一个服务器-在输入框里添加MJROBOT:https://discord.com/oauth2/authorize?client_id=936929561302675456&permissions=2147601472&scope=applications.commands%20bot-输入/→选择imagine开始写prompt-prompt使用
- Java常见面试题2
七禾页话
java面试java算法
Java常见面试题面向对象和面向过程的区别面向对象(POP):将方法和数据封装为对象作为程序的基本单元,提炼出封装继承多态来作为代码指导,注重代码灵活性和复用性面向过程(OOP):将过程作为基本程序的基本单元,过程对应到代码中就是函数,将函数和数据分离,注重步骤和流程对象实体和对象引用有什么不同Personperson=newPerson()你尝试打印person变量本身,输出可能是类似于"Per
- (九)ROS运行管理
PaLu-LvL
ROS从入门到实践机器人c++ubuntu学习
前言1.ROS是多进程(节点)的分布式框架,一个完整的ROS系统实现:可能包含多台主机;每台主机上又有多个工作空间(workspace);每个的工作空间中又包含多个功能包(package);每个功能包又包含多个节点(Node),不同的节点都有自己的节点名称;每个节点可能还会设置一个或多个话题(topic)...2.在多级层深的ROS系统中,其实现与维护可能会出现一些问题,比如,如何关联不同的功能包
- Node.js - Express框架
蒜蓉大猩猩
Node.jsnode.jsexpress后端架构
1.介绍Express是一个基于Node.js的Web应用程序框架,主要用于快速、简便地构建Web应用程序和API。它是目前最流行的Node.jsWeb框架之一,具有轻量级、灵活和功能丰富的特点。核心概念包括路由,中间件,请求与响应,以及模板引擎支持2.Express应用的使用通过npm进行安装express包npminstallexpress示例:以下是一个最简单的Express应用程序cons
- 实战设计模式之命令模式
希望_睿智
实战设计模式系列设计模式命令模式软件工程架构设计系统架构
概述命令模式是一种行为设计模式,用于将请求封装成对象,从而使我们可以用不同的请求对客户进行参数化。简单来说,命令模式就是把一个请求转换为一个包含所有关于这个请求信息的对象。这样,就可以像传递其他对象一样传递这个请求,并且可以在适当的时间和地点执行它。命令模式主要适用于以下几种应用场景。1、需要支持撤销、重做操作的应用程序,比如:文本编辑器、绘图程序等。2、操作可以被放入队列中,并按顺序或特定条件执
- .net链接mysql简单而高效
天堂镇的幽灵
.netmysqlandroid
usingSystem;usingSystem.Collections.Generic;usingSystem.Data.SqlClient;usingSystem.Data;usingSystem.Linq;usingSystem.Web;usingMySql.Data;usingMySql.Data.MySqlClient;usingSystem.Configuration;namespace
- sql统计相同项个数并按名次显示
朱辉辉33
javaoracle
现在有如下这样一个表:
A表
ID Name time
------------------------------
0001 aaa 2006-11-18
0002 ccc 2006-11-18
0003 eee 2006-11-18
0004 aaa 2006-11-18
0005 eee 2006-11-18
0004 aaa 2006-11-18
0002 ccc 20
- Android+Jquery Mobile学习系列-目录
白糖_
JQuery Mobile
最近在研究学习基于Android的移动应用开发,准备给家里人做一个应用程序用用。向公司手机移动团队咨询了下,觉得使用Android的WebView上手最快,因为WebView等于是一个内置浏览器,可以基于html页面开发,不用去学习Android自带的七七八八的控件。然后加上Jquery mobile的样式渲染和事件等,就能非常方便的做动态应用了。
从现在起,往后一段时间,我打算
- 如何给线程池命名
daysinsun
线程池
在系统运行后,在线程快照里总是看到线程池的名字为pool-xx,这样导致很不好定位,怎么给线程池一个有意义的名字呢。参照ThreadPoolExecutor类的ThreadFactory,自己实现ThreadFactory接口,重写newThread方法即可。参考代码如下:
public class Named
- IE 中"HTML Parsing Error:Unable to modify the parent container element before the
周凡杨
html解析errorreadyState
错误: IE 中"HTML Parsing Error:Unable to modify the parent container element before the child element is closed"
现象: 同事之间几个IE 测试情况下,有的报这个错,有的不报。经查询资料后,可归纳以下原因。
- java上传
g21121
java
我们在做web项目中通常会遇到上传文件的情况,用struts等框架的会直接用的自带的标签和组件,今天说的是利用servlet来完成上传。
我们这里利用到commons-fileupload组件,相关jar包可以取apache官网下载:http://commons.apache.org/
下面是servlet的代码:
//定义一个磁盘文件工厂
DiskFileItemFactory fact
- SpringMVC配置学习
510888780
springmvc
spring MVC配置详解
现在主流的Web MVC框架除了Struts这个主力 外,其次就是Spring MVC了,因此这也是作为一名程序员需要掌握的主流框架,框架选择多了,应对多变的需求和业务时,可实行的方案自然就多了。不过要想灵活运用Spring MVC来应对大多数的Web开发,就必须要掌握它的配置及原理。
一、Spring MVC环境搭建:(Spring 2.5.6 + Hi
- spring mvc-jfreeChart 柱图(1)
布衣凌宇
jfreechart
第一步:下载jfreeChart包,注意是jfreeChart文件lib目录下的,jcommon-1.0.23.jar和jfreechart-1.0.19.jar两个包即可;
第二步:配置web.xml;
web.xml代码如下
<servlet>
<servlet-name>jfreechart</servlet-nam
- 我的spring学习笔记13-容器扩展点之PropertyPlaceholderConfigurer
aijuans
Spring3
PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是BeanFactoryPostProcessor接口的一个实现。关于BeanFactoryPostProcessor和BeanPostProcessor类似。我会在其他地方介绍。PropertyPlaceholderConfigurer可以将上下文(配置文件)中的属性值放在另一个单独的标准java P
- java 线程池使用 Runnable&Callable&Future
antlove
javathreadRunnablecallablefuture
1. 创建线程池
ExecutorService executorService = Executors.newCachedThreadPool();
2. 执行一次线程,调用Runnable接口实现
Future<?> future = executorService.submit(new DefaultRunnable());
System.out.prin
- XML语法元素结构的总结
百合不是茶
xml树结构
1.XML介绍1969年 gml (主要目的是要在不同的机器进行通信的数据规范)1985年 sgml standard generralized markup language1993年 html(www网)1998年 xml extensible markup language
- 改变eclipse编码格式
bijian1013
eclipse编码格式
1.改变整个工作空间的编码格式
改变整个工作空间的编码格式,这样以后新建的文件也是新设置的编码格式。
Eclipse->window->preferences->General->workspace-
- javascript中return的设计缺陷
bijian1013
JavaScriptAngularJS
代码1:
<script>
var gisService = (function(window)
{
return
{
name:function ()
{
alert(1);
}
};
})(this);
gisService.name();
&l
- 【持久化框架MyBatis3八】Spring集成MyBatis3
bit1129
Mybatis3
pom.xml配置
Maven的pom中主要包括:
MyBatis
MyBatis-Spring
Spring
MySQL-Connector-Java
Druid
applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?>
&
- java web项目启动时自动加载自定义properties文件
bitray
javaWeb监听器相对路径
创建一个类
public class ContextInitListener implements ServletContextListener
使得该类成为一个监听器。用于监听整个容器生命周期的,主要是初始化和销毁的。
类创建后要在web.xml配置文件中增加一个简单的监听器配置,即刚才我们定义的类。
<listener>
<des
- 用nginx区分文件大小做出不同响应
ronin47
昨晚和前21v的同事聊天,说到我离职后一些技术上的更新。其中有个给某大客户(游戏下载类)的特殊需求设计,因为文件大小差距很大——估计是大版本和补丁的区别——又走的是同一个域名,而squid在响应比较大的文件时,尤其是初次下载的时候,性能比较差,所以拆成两组服务器,squid服务于较小的文件,通过pull方式从peer层获取,nginx服务于较大的文件,通过push方式由peer层分发同步。外部发布
- java-67-扑克牌的顺子.从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的.2-10为数字本身,A为1,J为11,Q为12,K为13,而大
bylijinnan
java
package com.ljn.base;
import java.util.Arrays;
import java.util.Random;
public class ContinuousPoker {
/**
* Q67 扑克牌的顺子 从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。
* 2-10为数字本身,A为1,J为1
- 翟鸿燊老师语录
ccii
翟鸿燊
一、国学应用智慧TAT之亮剑精神A
1. 角色就是人格
就像你一回家的时候,你一进屋里面,你已经是儿子,是姑娘啦,给老爸老妈倒怀水吧,你还觉得你是老总呢?还拿派呢?就像今天一样,你们往这儿一坐,你们之间是什么,同学,是朋友。
还有下属最忌讳的就是领导向他询问情况的时候,什么我不知道,我不清楚,该你知道的你凭什么不知道
- [光速与宇宙]进行光速飞行的一些问题
comsci
问题
在人类整体进入宇宙时代,即将开展深空宇宙探索之前,我有几个猜想想告诉大家
仅仅是猜想。。。未经官方证实
1:要在宇宙中进行光速飞行,必须首先获得宇宙中的航行通行证,而这个航行通行证并不是我们平常认为的那种带钢印的证书,是什么呢? 下面我来告诉
- oracle undo解析
cwqcwqmax9
oracle
oracle undo解析2012-09-24 09:02:01 我来说两句 作者:虫师收藏 我要投稿
Undo是干嘛用的? &nb
- java中各种集合的详细介绍
dashuaifu
java集合
一,java中各种集合的关系图 Collection 接口的接口 对象的集合 ├ List 子接口 &n
- 卸载windows服务的方法
dcj3sjt126com
windowsservice
卸载Windows服务的方法
在Windows中,有一类程序称为服务,在操作系统内核加载完成后就开始加载。这里程序往往运行在操作系统的底层,因此资源占用比较大、执行效率比较高,比较有代表性的就是杀毒软件。但是一旦因为特殊原因不能正确卸载这些程序了,其加载在Windows内的服务就不容易删除了。即便是删除注册表中的相 应项目,虽然不启动了,但是系统中仍然存在此项服务,只是没有加载而已。如果安装其他
- Warning: The Copy Bundle Resources build phase contains this target's Info.plist
dcj3sjt126com
iosxcode
http://developer.apple.com/iphone/library/qa/qa2009/qa1649.html
Excerpt:
You are getting this warning because you probably added your Info.plist file to your Copy Bundle
- 2014之C++学习笔记(一)
Etwo
C++EtwoEtwoiterator迭代器
已经有很长一段时间没有写博客了,可能大家已经淡忘了Etwo这个人的存在,这一年多以来,本人从事了AS的相关开发工作,但最近一段时间,AS在天朝的没落,相信有很多码农也都清楚,现在的页游基本上达到饱和,手机上的游戏基本被unity3D与cocos占据,AS基本没有容身之处。so。。。最近我并不打算直接转型
- js跨越获取数据问题记录
haifengwuch
jsonpjsonAjax
js的跨越问题,普通的ajax无法获取服务器返回的值。
第一种解决方案,通过getson,后台配合方式,实现。
Java后台代码:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String ca
- 蓝色jQuery导航条
ini
JavaScripthtmljqueryWebhtml5
效果体验:http://keleyi.com/keleyi/phtml/jqtexiao/39.htmHTML文件代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery鼠标悬停上下滑动导航条 - 柯乐义<
- linux部署jdk,tomcat,mysql
kerryg
jdktomcatlinuxmysql
1、安装java环境jdk:
一般系统都会默认自带的JDK,但是不太好用,都会卸载了,然后重新安装。
1.1)、卸载:
(rpm -qa :查询已经安装哪些软件包;
rmp -q 软件包:查询指定包是否已
- DOMContentLoaded VS onload VS onreadystatechange
mutongwu
jqueryjs
1. DOMContentLoaded 在页面html、script、style加载完毕即可触发,无需等待所有资源(image/iframe)加载完毕。(IE9+)
2. onload是最早支持的事件,要求所有资源加载完毕触发。
3. onreadystatechange 开始在IE引入,后来其它浏览器也有一定的实现。涉及以下 document , applet, embed, fra
- sql批量插入数据
qifeifei
批量插入
hi,
自己在做工程的时候,遇到批量插入数据的数据修复场景。我的思路是在插入前准备一个临时表,临时表的整理就看当时的选择条件了,临时表就是要插入的数据集,最后再批量插入到数据库中。
WITH tempT AS (
SELECT
item_id AS combo_id,
item_id,
now() AS create_date
FROM
a
- log4j打印日志文件 如何实现相对路径到 项目工程下
thinkfreer
Weblog4j应用服务器日志
最近为了实现统计一个网站的访问量,记录用户的登录信息,以方便站长实时了解自己网站的访问情况,选择了Apache 的log4j,但是在选择相对路径那块 卡主了,X度了好多方法(其实大多都是一样的内用,还一个字都不差的),都没有能解决问题,无奈搞了2天终于解决了,与大家分享一下
需求:
用户登录该网站时,把用户的登录名,ip,时间。统计到一个txt文档里,以方便其他系统调用此txt。项目名
- linux下mysql-5.6.23.tar.gz安装与配置
笑我痴狂
mysqllinuxunix
1.卸载系统默认的mysql
[root@localhost ~]# rpm -qa | grep mysql
mysql-libs-5.1.66-2.el6_3.x86_64
mysql-devel-5.1.66-2.el6_3.x86_64
mysql-5.1.66-2.el6_3.x86_64
[root@localhost ~]# rpm -e mysql-libs-5.1
151 Comments
Thanks for the code, it works nicely.
That is nice, very useful.
Any chance of it being submitted as a patch to the S2 team so that it can be ‘polished’ (Javadoc’ced and suchlike) and included in the core, similar to the way that Spring provides integration test support classes in the spring-mock.jar library?
Cheers
Rick
Pretty nice. I do believe this is one of the places where Struts 2.0 could offer a lot more developer support. I have been tackling this issue for sometime and written also some utility classes to simplify Struts 2.0 + Spring unit testing…
Here’s my take on it:
http://fassisrosa.blogspot.com/2007/03/unit-testing-struts-20-part-2.html
Thank you, it works great. You can also set the session into invocationContext:
protected static HashMap session = new HashMap();
// …
protected Object createAction(Class clazz, String namespace, String name)
throws Exception {
// …
proxy.getInvocation().getInvocationContext().setParameters(new HashMap());
proxy.getInvocation().getInvocationContext().setSession(session);
//…
}
This code has helped me a lot to get my action tests up and running. Thank you very much. A little problem remains, though, as we are using tiles too. When ever I try to execute an action that has as result type “tiles” I get an NPE in org.apache.struts2.view.tiles.TileResult.doExecute. It looks like the tiles listener (configured in web.xml) is not loaded. How does your code load web.xml actually (if at all)?
Mike, the web.xml is not being loaded at all. I didn’t find the need for it in my test cases but that would be an excellent feature. If I have some time I’ll see where/how it can be loaded, if you figure it out, please post the solution…
have you got any solution for loading web.xml??
This code is very helpful! It is exactly what I was looking for. However, I also have the same problem with tiles (as Mike above). If someone discovers the solution please post. I was going down the route of putting the tiles.xml in the ConfigurationManager, but I think this is the wrong path.
This is great thankyou!
My web application uses a servlet filter to maintain my jpa entity manager open in my views (org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter). I’m new to unit testing and wondered how i could modify your base class so that my filter gets inluded before calling the struts dispatcher. I am guessing that this is a similar problem to the tiles problem that is described in a previous post, ie the need to load web.xml.
I’m using Struts2 without Spring. And I would like to know how can I do a junit test using struts2??
Thanks in advance
Very good tutorial and it was very useful for me to test the complete flow in my application Thanks a lot.
I cannot find an invoke() method on the proxy reference in your testValidation()example. Also, I had to modify the method signature of protected T createAction(Class clazz, String namespace, String name) as follows protected T createAction(Class clazz, String namespace, String name)
Can you explain please?
Thanks and great work!
I see what happened to your source code now! the got sripped down on account of the HTML symbols! I have wrapped the method signature inside tags and it looks fine
protected createAction(Class clazz, String namespace, String name)
Now then, can you tell me why I am unable to find the invoke method on my proxy reference in the validation test code?
Sweet examples brother,
Scott
Hello Scott
I am getting a compile error on the method signature can you post the correct method signature plz?
— Error (T) cannot be resolved :
protected T createAction(Class clazz, String namespace, String name)
— Error (T) cannot be resolved :
return (T) proxy.getAction();
Can you tell me how to get around the error caused by this jndi snafu? This is being thrown from the setUp() at appContext.refresh();
Hi Scott, that should read proxy.execute(), not invoke(). I’ve fixed the example. Thanks for pointing out the error.
Sweet! Is there a way to get the model from the action post execute method call?
What do you mean? The return value of createAction() is the action class. Whatever public methods are available in your action are available during the tests. Just have a method which returns a model object in your action..
Consider the following test:
PayrollUpdateAction action = createAction(PayrollUpdateAction.class,
“/pr”, “PayrollUpdate_notes”);
action.setId(123L);
String result = proxy.execute();
PayrollUpdateTO model = action.getModel();
System.out.println(model);
assertEquals(“notes”,result );
The model that prints is null! Spring injected the model and it was a live reference during the execute() behavior! I guess my question is one of accessing the action before it has wound it’s way through the interceptors during the return cycle
My bad! I did not have Spring injecting the model. Sorry if you looked into this already.
Peace,
Scott
createAction(PayrollUpdateAction.class,“/pr”, “PayrollUpdate_notes”);
Are you only requiring the class name because Java Generics require it?
Yup, only reason. Just to avoid a cast in the code that calls createAction(), it’s a little neater (I think).
I agree this makes your factory method much cleaner! I really appreciate you offering up this solution. It is easy to see you are a very sharp cat.
I have an Action that extends a parent who implements SessionAware. When I pass my subclass to the createAction and use the proxy to invoke it, I am getting a null pointer on the session Map. Should the setSession()be getting called if it is in the interceptor stack?
Scott
I haven’t worked with SessionAware so I’m not sure when it gets invoked, I just use the org.apache.struts2.ServletActionContext class to get hold of the request/response objects.
All the interceptors are being called, however, since we are using a MockServletContext, naturally the request and session are Mocks too. I am trying to test an Action that implements these *aware* interfaces and of course the request and session maps are null. What would be the most natural way to push my own maps into these variables? Does it seem okay to simply call the setters on the action itself?
Thanks,
Scott
One more comment on the interceptor invocation. I have the following test running:
MemberMaintenance action = createAction(MemberMaintenance.class,”/member”, “MemberMaintenance_add”);
(MemberMaintenance) proxy.getAction()).setSession(new HashMap());
Map p = new HashMap();
p.put(“id”, “1″);
proxy.getInvocation().getInvocationContext().setParameters(p);
String nextStep = proxy.execute();
(ActionSupport) proxy.getAction()).getFieldErrors();
and when the SessionAware interceptor is invoked, it is “resetting” my session Map to null! I have fixed it for the moment by changing the setSession(Map session) to check for a null Map being passed in. This really calls into question the advantage of having the interceptors included on the proxy.execute() test though. Comments?
Scott
Hello,
I’m completely new to unit testing with struts and I’m having difficulty getting this example to work… Is this designed to run in the container or not? I thought not, but now I’m unsure. If it’s in container, can anyone point me to some examples of setting up container testing with junit?
I’m also seeing an error saying either my applicationContext.xml cannot be found, or there’s a connection timeout parsing the xml. The file not found is fair enough, but can anyone suggest a reason for a connection timeout?
Jason, this is not designed to run in a container. I don’t think running unit tests in a container is the way to go, you’re testing discrete action functionality, not how the container might behave.
As for the appplicationContext.xml not being found, remember that they’re being loaded from the classpath using XmlWebApplicationContext so make sure your application context configuration is in your classpath and referenced correctly in config[]. If you prefer to load them from the file system instead, you can just override XmlWebApplicationContext.getResource().
Thanks for your help. I seem to be locating the appContext ok now, but I have another question: No where in the code do you specify the location of the struts.xml. Is this also assumed to be on the classpath? Is there a way to load this from the filesystem if necessary?
I’m getting an error now where none of my action mappings can be resolved, so I assume struts.xml to not being picked up.
Do you have the link to the source code?
It doesn’t seem to work with Struts 2.0.9. Thanks really.
It’s working fine with 2.0.9 for me, might want to post the error you’re getting.
Get this error:
Unable to create SAX parser – Class: org.gjt.xpp.jaxp11.SAXParserFactoryImpl
etc etc etc
Caused by: javax.xml.parsers.ParserConfigurationException: validation is not supported
at org.gjt.xpp.jaxp11.SAXParserFactoryImpl.newSAXParser(SAXParserFactoryImpl.java:100)
at com.opensymphony.xwork2.util.DomHelper.parse(DomHelper.java:109)
… 21 more
The app code works on the server. Is some jar missing to my local test?
The line:
StrutsSpringObjectFactory.setObjectFactory(ssf);
Does not works in struts 2.1 snapshot.
I trace the code and find out that ObjectFactory in xworks 2.1 drop the singleton pattern. Would you mind giving me any suggestion to do the right same things in struts 2.1 (+ xworks 2.1)
I’ve updated the source code to make it a little simpler, you don’t need StrutsSpringObjectFactory anymore. Try it again and let me know.
Your sample is different from my case. Since I have other types of test that use spring, and I don’t want to startup more than one spring application context. In short, I wish to have a way that put a spring application context into struts context by hand when test setup, just as your previous sample that I can put the application context in a new StrutsSpringObjectFactory and assign the object factory to struts context. Is there any other way to do that? Thanks for your help.
What changes would need to be made if I’m not using Spring? Thanks guys, tons of help!
Hi there
I have recently started developing Struts 2 and I am enjoying it, thanks to articles like these. I have used the base class and I am getting a NPE when it comes to tiles..and i see people have posted about this before and I was wondering if someone has done a solution and if so is there any sample code I could have a look at?
Thanks
I am also having the same problem…Can anyone pls help me?…
Hi, thanks for this nice article. It helped me a lot.
Maybe you can fix the typo(?) in PersonActionTest line 12 (pa->action).
I am using Struts 2.0.11 with Tiles 2.0.4 (TilesDecorationFilter) and I am not facing the problems stated above. But I am extremely new to all the stuff ^^ so don’t trust me too much
Thanks Felix, I’ve fixed the typo.
I am also struggling to get this to work without Springs (just struts2). I know that isn’t the purpose of this article, but its so close
Hi there
I am trying this out for a project that uses freemarker and I am getting a ton of warning messages – I am testing it in intellij idea
…
java.io.FileNotFoundException: class path resource [template/simple/common-attributes_en_US.ftl] cannot be resolved to URL because it does not exist
…
2007-11-28 16:45:10,546 WARN [org.springframework.mock.web.MockServletContext:MockServletContext.java:264] : Couldn’t determine real path of resource class path resource [template/xhtml/form-close-validate.ftl]
java.io.FileNotFoundException: class path resource [template/xhtml/form-close-validate.ftl] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/C:/Documents%20and%20Settings/jon/.m2/repository/org/apache/struts/struts2-core/2.0.11/struts2-core-2.0.11.jar!/template/xhtml/form-close-validate.ftl
…
any tips?
Hi
I am learning struts2. this is realy good artical for me.
if you have more artical related to struts2,Spring and hibernate published it.
Rishi
Hi,
Really good example. Had a quick (and probably stupid) question though. How do you invoke a method in the action other than “execute”? I have an action class with all my CRUD methods in there and want to test each one with the full interceptor stack etc.
Thanks,
Mohammed
Mohammed, you can define the configuration in your struts.xml:
<action name="myAction" class="MyClass" method="myMethod"/>
or you can just invoke myAction like this: myAction!myMethod.action and myMethod will be called.
can you pls tell me what to do when action returns a tiles type result??
Thanks,
Do you, or anyone else have this working with Maven 2?
I’m having problems…
(NB, my other unit tests work fine – just cant test action classes at the moment).
I wasnt sure how to get the XML files (Spring, Struts etc) onto the test classpath, so ended up copying them to src/test/resources (there has to be a better way!)
After doing that, i’m getting the following error
Unable to load bean: type:org.apache.struts2.components.template.TemplateEngine class:org.apache.struts2.components.template.JspTemplateEngine – bean – jar:file:/C:/Documents%20and%20Settings/abdealim/.m2/repository/org/apache/struts2/struts2-core/2.0.9/struts2-core-2.0.9.jar!/struts-default.xml:34:150
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.register(XmlConfigurationProvider.java:208)
…
Add the struts2-core-2.0.9.jar in your pom file and test once ,
Also you can add the same in properties-> Javabuild path-> add external jars-> add this jar and test.
Hey,
I tried running the test customized to my application, but I am encountering an issue of Infinite Recursion Detected. I guess its something related to auto chaining not working, but am not sure. Appreciate your help in this regard
I am getting the same error when running the junit test.
Infinite recursion detected: [/login!input, /exceptionHandler, /exceptionHandler] – [unknown location]
at com.opensymphony.xwork2.ActionChainResult.execute(ActionChainResult.java:207)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:348)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:253)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:50)
at com.opensymphony.xwork2.ActionChainResult.execute(ActionChainResult.java:229)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:348)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:253)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:50)
at gov.glin.web.struts.action.LoginActionTest.testValidLogin(LoginActionTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:69)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
here is the entry in the struts.xml
{ “input”, “login” }
/login/login.ftl
/home.action
/changePassword.action?user=${user.userId}
Re: 45.
src/test/resources and src/main/resources is the best way to put stuff in your classpath, not sure why you don’t like that. You can also define additional resources location in Maven if you need to.
Hi,
I’m very new to java, struts, spring, etc..
And i’m getting trouble to get this test working with my struts actions. I’m using eclipse and when I run the test I see from the Junit tab this error:
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:99)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:317)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:125)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:141)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:123)
at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:91)
at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:94)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:292)
at org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:156)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:246)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:184)
at com.aix2.test.BaseStrutsTestCase.setUp(BaseStrutsTestCase.java:117)
at junit.framework.TestCase.runBare(TestCase.java:125)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:128)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
I tryed to test if I was pointing to the right file and if it is readable putting this code snipet in my class constructor:
File f = new File("WEB-INF/applicationContext.xml");
if (f.exists() && f.isFile()) {
try {
System.out.println("file exists: " + f.getCanonicalPath());
} catch (Exception e) {
e.printStackTrace();
}
if (f.canRead()) {
System.out.println("readable archive.");
}
}
which prints:
“file exists.
readable archive”
and then:
web-15:23:54,968 DEBUG com.aix.estagio.AtividadesEstagioAction:41 - AtividadesEstagioActionTest() - start
web-15:23:54,984 DEBUG com.aix2.test.BaseStrutsTestCase:88 - createAction(Class, String, String) - Erro ao criar ActionProxy: java.lang.NullPointerException
web-15:23:54,984 ERROR com.aix2.test.BaseStrutsTestCase:90 - createAction(Class, String, String)
java.lang.NullPointerException
at com.aix2.test.BaseStrutsTestCase.createAction(BaseStrutsTestCase.java:76)
at com.aix.test.webgiz.AtividadesEstagioActionTest.(AtividadesEstagioActionTest.java:45)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
at junit.framework.TestSuite.createTest(TestSuite.java:131)
at junit.framework.TestSuite.addTestMethod(TestSuite.java:114)
at junit.framework.TestSuite.(TestSuite.java:75)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestLoader.getTest(JUnit3TestLoader.java:102)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestLoader.loadTests(JUnit3TestLoader.java:59)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:445)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
after debugging I’ve found that the dispatcher object is null when in the createAction method.
When is this object instantiated?
Do you have any ideas on how to get this working for my case?
Many thanks and sorry for the bad english.
use like this:
CONFIG_LOCATIONS = “file:D:\\开发中项目\\dsunit\\WebRoot\\WEB-INF\\classes\\applicationContext.xml”;
Hope you success.
dalto, you’re having a classpath issue. Just make sure your tests can find the application context at /WEB-INF/applicationContext.xml. Or you can tell Spring where to look for the files as shown in the example.
Hi arsenalist,
appreciate your inputs on issue 46 pls.
Sri, that to me looks like something wrong with your action configuration which is causing a recursion between the login!input action and your exceptionHandler. Is your exception handler by any chance redirecting to login!input and in turn login!input is throwing n exception thus causing the recursion?
I believe the action is being invoked correctly which indicates that the test is setup fine, it’s just what happens after that is the problem.
here is my struts entry
{ “input”, “login” }
/login/login.ftl
/home.action
/changePassword.action?user=${user.userId}
and my applicationContext entry
I dont know from where the input method is invoked, and why my action fails which in turn calls exceptionHandler. frustrated with this.
applicationContext
struts entry
{ “input”, “login” }
/login/login.ftl
/home.action
/changePassword.action?user=${user.userId}
am not sure why my application entry and struts entry is cropped
This blog has some trouble dealing with XML, you’ll have to escape it when posting code. I think the “input” method is automatically invoked by Struts at some point (I could be wrong), you should try renaming the input method to something more precise and see what the behavior is.
thanks for the reply!
i’m new to java and i can’t understand what the classpath have to do with this issue.. do i have to add my project directory to the classpath?
i already tried to fix this by specifying to where the file is like the exemple and it keep throwing the same error.. by the way, i only have the applicationContext.xml file and not the security one, can this cause any problem?
i’ve added the MockServletContext package directory to the classpath, keeps throwing the same error in the setUp() method.
i solved it by referencing the file this way:
file///c:/workpath/project/WEB-INF/applicationContext.xml
nice article, btw
hi arsenalist,
Issue 46 I could resolve that issue now, the problem was there was an NPE which was thrown in ContextInterceptor because I didnt set the Session in the BaseTestCase
proxy.getInvocation().getInvocationContext().setSession(sessionMap);
and hence the infinite recursion. Good Lord I spent lot of time debugging for this. My bad.
Thanks for your help arsenal.
Thanks for posting this, in an ocean of mediocrity it is nice to stumble across the odd pearl.
I’m prototyping my first struts2 app right now and having successfully configured actions/results using annotations I would like to be able to test them. Unfortunately as it stands and using your base test class I am unable to do that. Everything works as expected if I add the actions/results into struts.xml. I have already spent some time wading through the Dispatcher source and find myself very little the wiser. I thought perhaps by loading actionPackages in the initParams parameter of the Dispatcher constructor it might all magically start working. Unfortunately I’m still relatively new to java (from c#) and I really want to understand what I’m doing rather than rely on magic. I would really appreciate a few pointers.
David, what’s the problem?
Well, I would like to know how to enable your BaseStrutsTestCase class to work with action/result annotations.
I also develop an application using Tiles. It would be really neccessary to mock out the TilesResult because these would be tested independently.
I would also like to test Preparer classes, but my preparers could do nothing but return action results so that they can be tested.
Hi,
I’m getting this error, and have no idea where to even start looking for the problem. I’m using Maven 2, JUnit 4, Struts 2 + Spring.
Unable to load bean: type:org.apache.struts2.components.template.TemplateEngine class:org.apache.struts2.components.template.JspTemplateEngine – bean – jar:file:/C:/Documents%20and%20Settings/abdealim/.m2/repository/org/apache/struts2/struts2-core/2.0.9/struts2-core-2.0.9.jar!/struts-default.xml:34:150
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.register(XmlConfigurationProvider.java:208)
at org.apache.struts2.config.StrutsXmlConfigurationProvider.register(StrutsXmlConfigurationProvider.java:101)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reload(DefaultConfiguration.java:131)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:52)
at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:395)
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:452)
at com.sentaca.telusreporting.web.BaseStrutsTestCase.setUp(BaseStrutsTestCase.java:95)
at com.sentaca.telusreporting.web.UserManagementActionTestCase.setUp(UserManagementActionTestCase.java:12)
at junit.framework.TestCase.runBare(TestCase.java:132)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:81)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:62)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:138)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:125)
at org.apache.maven.surefire.Surefire.run(Surefire.java:132)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:290)
at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:818)
Caused by: java.lang.NoClassDefFoundError: javax/servlet/jsp/JspWriter
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
at java.lang.Class.getDeclaredConstructors(Class.java:1808)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.register(XmlConfigurationProvider.java:198)
… 25 more
Hey there – I guess your attention is currently elsewhere. I am wondering if you have had any opportunity to think about how your BaseStrutsTestCase could be made annotation-aware. I realise this may not be high on your list of priorities but I would certainly appreciate some pointers as to how I might go about this. I’m currently in the middle of a prototype exercise and I will need to revisit this soonish. Being able to test my actions is higher on my list of priorities than using annotations so I may need to revert to the xml-style configuration if I can’t get this working.
It is actually quite easy to make this base class annotation aware. Just add this before line 86 (in setUp()) in BaseStrutsTestCase:
HashMap params = new HashMap();
params.put("actionPackages", "your.action.package1,your.action.package1");
and then modify line 86 to read:
dispatcher = new Dispatcher(servletContext, params);
You basically need to tell the dispatcher to scan your classpath. actionPackages is the parameter which makes this happen in web.xml. If you want to understand why and how this works check out the Dispatcher code at Krugle:
http://www.krugle.org/kse/files/svn/svn.apache.org/struts/current/struts2/core/src/main/java/org/apache/struts2/dispatcher/Dispatcher.java
Thank you Hardy for that! I’ve updated the post.
Thanks Hardy, that would be worth a woot! Your timing is impeccable.
I’m getting this error when I run my JUnit Test class
java.lang.SecurityException: class “junit.framework.JUnit4TestCaseFacade”‘s signer information does not match signer information of other classes in the same package
at java.lang.ClassLoader.checkCerts(Unknown Source)
at java.lang.ClassLoader.preDefineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at org.junit.internal.runners.OldTestClassRunner$OldTestClassAdaptingListener.asDescription(OldTestClassRunner.java:41)
at org.junit.internal.runners.OldTestClassRunner$OldTestClassAdaptingListener.startTest(OldTestClassRunner.java:31)
at junit.framework.TestResult.startTest(TestResult.java:151)
at junit.framework.TestResult.run(TestResult.java:103)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:230)
at junit.framework.TestSuite.run(TestSuite.java:225)
at org.junit.internal.runners.OldTestClassRunner.run(OldTestClassRunner.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Any idea on what this means ? Thanks !
Ismath
Hi, just one idea to improve the code. In class PersonActionTest you use
assertEquals(result, “success”);
which will result in some misleading error messages by JUnit on failure, like
[junit] junit.framework.ComparisonFailure: expected: but was:
The JUnit API documentation states:
assertEquals(java.lang.String expected, java.lang.String actual)
So just flipping the variables will make things clearer.
Greets, Felix
This really works well, but I have an obstacle. We have custom validators and have placed the validators.xml file in the /WEB-INF/classes/ directory as prescribed. The site works fine, however, the test case for the action does not. Running against the action produces the exception: java.lang.IllegalArgumentException: There is no validator class mapped to the name myCustomValidator.
I’m not sure how to incorporate this into the above test configuration. Do you have a suggestion? Thanks!
Actually, I just figured it out, but perhaps you know a better way. I added:
ValidatorFactory.registerValidator(“myCustomValidator”, “x.y.z.web.validators.MyCustomValidator”);
as the first line in my unit test and it works. By the way, I’m also using your base test to get an action so that I can set up the validator context in other tests that test validators independently. It really made it easy. Thanks again.
good
Hi, thanks for this post. My colleagues and I are finding it very helpful.
Just one nit-picking I couldn’t resist though.
It seems you are using assert…() method’s parameters in reverse order. According to the API doc, ‘expected’ value should come first, then ‘actual’. I don’t think this would degrade the quality of tests in terms of accuracy, but for the people reading the tests (and adopting these in their own projects), it may be confusing at times since it goes against the usual convention.
Anyways, cheers for the Arsenal!
Hi,I am having struts2 + hibernate application no spring configuration.
I used the same abstract BaseStrutsTestCase class with only change to commented out this code from setUp() method
/*
if( applicationContext == null ) {
// this is the first time so initialize Spring context
servletContext = new MockServletContext();
servletContext.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
CONFIG_LOCATIONS);
applicationContext = (new ContextLoader()).initWebApplica
*/
Test cases works fine with struts2 application only.
But the only problem is that i am not able to pass the request parameters to the action class while able to pass the
params by SettingDomainObjects.
It means testInterceptorsBySettingDomainObjects() this is working fine while this is not testInterceptorsBySettingRequestParameters() from the above example.
Can anybody tell me what is the problem here ?
If we want to use a different struts xml than the default one (say, struts-test.xml) , it can be specified as :
params.put(“config”,”struts-default.xml,struts-plugin.xml,struts-test.xml”);
somebody copied your article word by word here http://itefforts.blogspot.com/2007/08/struts2-spring-junit.html
Hi all,
I´ve read the posts, and someone has the need to put in the CONFIG_LOCATIONS the web-xml?
I´ve there de JNDI datasources needed by Spring.
How, based in the example, could i load to the classpath the web.xml??
cheers
Bigster, to load config locations, you can just specify it using the way it’s shown in Line 75 of the setUp() method.
servletContext.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, CONFIG_LOCATIONS);
arsenalist,
That´s what i´ve tried :
private static final String CONFIG_LOCATIONS =
“WEB-INF/web.xml,”+ “hibernate.cfg.xml,” + “aplicationContext-dao.xml,” + “applicationContext-resources.xml,” + “applicationContext-service.xml,” + “applicationContext-struts.xml”;
it throws a FileNotfoundExecption, it don´t find tha web.xml in the WEB-INF folder.
any help?
use like this:
private static final String CONFIG_LOCATIONS =
“/WEB-INF/web.xml,”+ “/hibernate.cfg.xml,” + “/aplicationContext-dao.xml,” + “/applicationContext-resources.xml,” + “/applicationContext-service.xml,” + “/applicationContext-struts.xml”;
Hi. I’m trying to implement this solution, but i have problem with the import
“import org.springframework.mock.web.MockHttpServletRequest;”, don’t recognises and don’t exist in spring 2.0.4 jar file. Any idea?. Congratulations Arsenal and thank you for your article.
Resolved. The spring jar file does’n contain the mock jar, is only the core. Must be include the mock jar file in the classpath. Now i’m trying the test my classes. Thks.
Hi I am very new to struts2. I am using tiles and like to use your code to develop some test cases for my application. The problem is I was using any namespace tag before in the package area.
So when I use namespace tag and put some value in it, the body jsp displayed but not the left menu, top menu and etc.
Why other jsp are not getting displayed?
—Struts.xml———————————————–
myTest
Error
————————————————————
Tiles.xml
Hi I am very new to struts2. I am using tiles and like to use your code to develop some test cases for my application. The problem is I was using any namespace tag before in the package area.
So when I use namespace tag and put some value in it, the body jsp displayed but not the left menu, top menu and etc.
Why other jsp are not getting displayed?
—Struts.xml———————————————–
myTest
Error
————————————————————
Tiles.xml
---Struts.xml-----------------------------------------------
myTest
Error
------------------------------------------------------------
Tiles.xml
—Struts.xml———————————————–
package name=”vd” namespace=”/vd” extends=”something”
action name=”vdTest” class=”vdAction”
result type=”tiles” myTest result
result name=”error” type=”tiles” Error result
action>
package
————————————————————
Tiles.xml
definition name=”default” template=”/WEB-INF/jsp/default.jsp”
put-attribute name=”title” value=”Management System”
put-attribute name=”header” value=”/html/header.html”
put-attribute name=”menu” value=”/WEB-INF/jsp/menu.jsp”
put-attribute name=”footer” value=”/html/footer.html”
put-attribute name=”body” value=”/html/main.html”
definition>
definition name=”myTest” extends=”default”
put-attribute name=”body” value=”/WEB-INF/jsp/vdTest.jsp”
definition
Hi,
I’m trying to test Struts actions following this example and I’m getting type cast exception in the line:
PersonAction action = createAction(PersonAction.class, “/site”, “deletePerson”);
Exception message says “ActionSupport” cannot be cast to PersonAction.
Hi everyone,
I’m also running “testInterceptorsBySettingRequestParameters()” with no success. I’m using ognl expressions in the request parameter like “person.name”, “person.description” and the action is getting a null reference to the Person object.
I have the getter and setter for the person object. While debugging I found the request parameters are null.
Any help will be very much appreciated,
Thanks in advance
Karel, for #87 make sure your PersonAction class extends ActionSupport. I suspect #88 might be related too.
Hi,
The class in fact extends ActionSupport and I’m still getting the error.
The other thing is that the Person object doesn’t get populated in the PersonAction class after setting request parameter “person.name” and “person.description” parameters in the request.
I’m following this example line by line with the modification of having a Person object that gets populated from the request in the Action bean.
Thanks for your quick feedback.
Cheers,
Karel
Karen – make sure you have the proper interceptors in your stack. This example is working fine for me using the default struts.xml configuration. Maybe its time to whip out the debugger and see what interceptors are being invoked.
So, I am seeing the same issue with MockHttpServletRequest parameters not making it through the Parameters interceptor. I have traced the code pretty deep and it looks like the InvocationContext does not get a copy of the MockHttpServletRequest parameters. There is some interesting comments in ActionContext for setParameters(Map param), where it says “in a Servlet Environment this returns the HttpRequest parameters, otherwise it returns a Map” (paraphrase). So I trying to figure out where this all gets determined. My guess is the Dispatcher so I am headed in that direction.
While I am doing that, it sounds like people are getting this (request.addParameter(…)) to work. Mike, what version of Struts are you using? What plugins? How are you executing your unit tests? Anything else about your Struts/Testing environment that is not likely to be shared by others?
Ok, so I did not figure out why the parameters are not getting copied from the ServletRequest to the InvocationContext, but I have a workaround I think.
Try replacing:
request.addParameter(“id”,”1″)
with
Map params = new HashMap();
params.put(“id”,”1″);
proxy.getInvocation().getInvocationContext().setParameters(params);
java.lang.NullPointerException at org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:104)at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:178)
-
-
- at
vms.junit.test.LoginActionTest.testInterceptorsBySettingDomainObjects(LoginActionTest.java:29)
My LoginActionTest is——————-
package vms.junit.test;
import java.util.Map;
import vms.action.LoginAction;
import vms.model.User;
public class LoginActionTest extends BaseStrutsTestCase {
public LoginActionTest(String name) {
super(name);
}
public void testInterceptorsBySettingDomainObjects() throws Exception {
LoginAction action = createAction(LoginAction.class,
“/”, “Login”);
User user = new User();
user.setFirstName(“vidit”);
user.setLastName(“kumar”);
action.setUser(user);
String result = proxy.execute();
assertEquals(result, “success”);
}
}
I have tiles listener in my web.xml…I dont know why I am getting this error.
Any help will be much appreciated.
Some people have reported success using that with Tiles, others have not. The issue here is that the tiles config isn’t being read because it can’t find it in the classpath…
Sorry, I stopped using Tiles a long time ago in favor of Sitemesh.
Hi Arsenalist
thanks for the quick reply. I am loading tiles config in the same way I am loading application-Context and dataAccessContext
private static final String CONFIG_LOCATIONS = “classpath:/WEB-INF/applicationContext.xml”
+ “, classpath:/WEB-INF/dataAccessContext.xml”
+ “, classpath:/WEB-INF/tiles.xml ” ;
Is there any other way to load tiles config file.
Some time ago now but…
For issues 45 & 64 – the JspTemplateEngine is dependant on the jsp-api.jar
Make sure this is available on the class path.
I have a problem with applicationContext.xml file’s configuration. My applicationContext.xml file is not under META-INF, so I change this part :
private static final String CONFIG_LOCATIONS = “META-INF/applicationContext-app.xml,” +”META-INF/applicationContext-security.xml”;
to
private static final String CONFIG_LOCATIONS = “WEB-INF/applicationContext.xml”;
The error is :
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml] at
Moreover, I don’t have a file named applicationContext-security.xml.
I am sure that applicationContext.xml is in the correct place, so what is the problem? Should I do some change on it?
The applicationContext.xml file :
I have solved my problem
I just wrote :
private static final String CONFIG_LOCATIONS = “file:WebContent/WEB-INF/applicationContext.xml”;
But I couldn’t understand the difference.
After I have solve the configuration problem, there is another problem about tiles. As some peope mentioned that the tiles integration causes NPE, I have the same problem, ant the trace is the same.. I have set the configuration file to
private static final String CONFIG_LOCATIONS = “file:src/struts.xml,file:WebContent/WEB-INF/tiles.xml” ; this, as suggested, but it did not work. How can I solve this problem ?
I do not have applicationContext file, I use struts.xml instead of it.
struts.xml :
tvq.NameCollector
tvq.ListTasks
/error.jsp
tvq.addTask
web.xml :
TVQ
struts2
org.apache.struts2.dispatcher.FilterDispatcher
struts2
/*
org.springframework.web.context.ContextLoaderListener
Tiles_Filter
org.apache.tiles.web.startup.TilesFilter
org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
/WEB-INF/tiles.xml
Tiles_Filter
/*
REQUEST
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
I have modified BaseStrutsTestCase.createAction to include request and response objects
protected T createAction(Class clazz,String namespace, String name, MockHttpServletRequest request,MockHttpServletResponse response)
Modified the following lines in the method
Map extraContext = dispatcher.createContextMap(request, response, null, servletContext);
ActionProxy proxy = dispatcher.getContainer().getInstance(
ActionProxyFactory.class).createActionProxy(namespace, name,
extraContext, true, false);
dropped these lines
proxy.getInvocation().getInvocationContext().
setParameters(new HashMap());
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
ServletActionContext.setRequest(request);
ServletActionContext.setResponse(response);
This will make sure whatever parameter is added to servlet request using addParameter method will end up in the Action domain objects.
I hope this solves Dusty’s problem
For the ones who want to integrate this unit test with tiles, I have found a tutorial-like post :
http://www.soft-gems.net/index.php?option=com_content&task=view&id=48&Itemid=33
However, It gave an exception like that:
org.apache.tiles.definition.NoSuchDefinitionException: tvq.ListTasks
The program works correctly, but I can not test it
I found a similar code sample to this at http://www.soft-gems.net/index.php?option=com_content&task=view&id=48, which included tiles support. I found that by adding the tiles config from the other example to the code on this page I stopped getting NPE’s in Tiles, although I’m still working through my tests to see if it breaks anything else.
To add tiles support, find this line in the existing code (currently line 80 in the listing above but it might change) :-
new JspSupportServlet().init(new MockServletConfig(servletContext));
and add the following code to define the location of your tiles.xml and sets up a Tile listener
servletContext.addInitParameter(BasicTilesContainer.DEFINITIONS_CONFIG, “WEB-INF/tiles.xml”);
final StrutsTilesListener tilesListener = new StrutsTilesListener();
final ServletContextEvent event = new ServletContextEvent(servletContext);
tilesListener.contextInitialized(event);
I cant claim any credit for the above, other than finding it and posting it here
Thanks for posting it. I was breaking my head on why tiles not getting initialized. Tried several configuration option in struts2 but nothing worked.
I am thinking of posting the same in several other places where people posted this issue. I saw several people had problems on the same lines.
Thanks.
Why we need to load tiles.xml for JUnit, are you trying to execute results? This is to know the requirement.
Thanks
Thank you so much!
This is exactly what I’ve been searching for hours.
It also serves as a good example to load any other ServletContextListener classes.
We are trying to use this to test action classes in an Struts/Spring/Hibernate application.
DriverManagerDataSource and LocalSessionFactoryBean are used.
I am receiving HibernateException that there is no active transaction. Any idea?
cat7,
I tried what you have suggested but It gave an error as I mentioned before:
org.apache.tiles.definition.NoSuchDefinitionException: tvq.ListTasks
What can be the problem?
Line 57-58
//do not execute the result after executing the action
proxy.setExecuteResult(true);
there is a bug inside this code
hi,
my StrutsActionTestCase is virtually a copy of your BaseStrutsTestCase. I use it first in TestLogin where everything works fine and than in TestRegister where this strange assertion error is thrown:
java.lang.AssertionError:
Unexpected method call put(“configurationReload-struts-default.xml”, true):
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:56)
at org.easymock.classextension.internal.ClassProxyFactory$1.intercept(ClassProxyFactory.java:74)
at com.opensymphony.xwork2.ActionContext$$EnhancerByCGLIB$$8aa46a90.put()
at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:110)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reload(DefaultConfiguration.java:152)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:52)
at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:395)
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:452)
at test.actions.StrutsActionTestCase.setUp(StrutsActionTestCase.java:94)
at test.actions.security.TestRegister.setUp(TestRegister.java:27)
StrutsActionTestCase.java:94 coresponds to BaseStrutsTestCase.java:90 which is the line with
dispatcher.init().
Why is the ActionContext an EasyMock-Mock-class???
the quickfix seems to be to reset the ActionContext in BaseStrutsTestCase.setUp() between line 71 and line 72:
protected void setUp() throws Exception
{
ActionContext.setContext( new ActionContext(new TreeMap()) );
if( applicationContext == null ) {
….
But there seems to be a bug somewhere!?
I am trying to unit test one action class which returns sucess…
I am getting this error…
-Info — Initializing Tiles2 container. . .
-WARN [org.apache.tiles.impl.BasicTilesContainer] – Unable to find configured definition ‘/WEB-INF/tiles.xml’
2008-08-07 13:51:19,583 INFO [org.apache.tiles.impl.BasicTilesContainer] – Tiles2 container initialization complete.
PS. session and request are *local* variable. Do not use the member variable of the same name.
I’m having the same Classpath problems that some have found (46).
On my setup, I have a unittests source folder (separate from both the src and WebContent).
String CONFIG_LOCATIONS = “WEB-INF/applicationContext.xml”;
doesn’t find the file (nor tiles.xml, for example). “WebContent/WEB-INF/…” doesn’t find it either.
I’ve also tried the full system path without any luck.
Everything works great if I copy-paste the xml files to the unittests source folder. But how can I reference the files in the WEB-INF folder?
Is Junit support Struts 2.0?
I am trying to write Junit Test Case for DAO’s but Objects are not created.
Thank you for this great post !
I’m new to this these technologies. so while I copied this class to run in my eclipse it is giving me 2 errors which is in “T” -no class exit..
how to resolve this.
I’ve been successfully using your BaseStrutsTestCase under TestNG with Struts-2.1.2 and Spring-2.5.6.
Pretty nice, thanks!
I was wondering how you handle the fact the service layer problem. In order to test your actions, you need to provide some persistent entity, right? If you want to keep away from the container, you’ve got to mock the Service layer in some ways so as to be able to return expected entity for your action.
How do you mock them? Do you use a specific tool?
My DAOs implement interfaces and I have a “real” implementation and a test implementation which I use during testing. I use XStream and a bunch of XML files to mock data coming from a database during testing.
Nice article, I tried the same but facing following issue when I try to run the JUnits
[junit] Running com.pg.site.actions.about.AboutUsActionTest
[junit] Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0 sec
[junit] Test com.pg.site.actions.about.AboutUsActionTest FAILED (crashed)
The message in the log is
junit.framework.AssertionFailedError: Forked Java VM exited abnormally. Please note the time in the report does not reflect the time until the VM exit.
If any of you faced such issue, can you please help me.
I implemented SessionAware interface in Action class and i just set the session using,
….
ServletActionContext.getContext().setSession(session);
ServletActionContext.setServletContext(servletContext);
……
and it works like magic
Hi Arsenalist, nice job!
I’ve implemented your framework and it’s been incredibly helpful. One question though: I’ve not been able to get it to add request parameters using your method in the example (request.addParameter(“id”, “123″)). The values just don’t get noticed by the interceptors. So, I’ve been doing it using the method that the base action uses (proxy.getInvocation().getInvocationContext().getParameters().put( …. ) ).
That works well, but it’s a little messy, because that particular parameters map requires all parameter values to be String[]s, not Strings, so i have to add extra lines into the code. Any idea what I might be doing wrong?
Cheers.
Just an extra note on my last post: I tried Girih’s method from 7/2/08, but I wasn’t able to get it work…
In the method definition:
protected T createAction(Class clazz, String namespace, String name)
For the class ‘T’ should i import the following class
import org.apache.poi.hssf.record.formula.functions.T;
In the method definition:
protected T createAction(Class clazz, String namespace, String name)
For the class ‘T’ should i import the following class
import org.apache.poi.hssf.record.formula.functions.T;
is this correct import?
T is a reference to any class in Java 1.5 generics. You don’t need to import anything.
Hi
I am trying to use your framework and is really usefull, in my case I am using struts2-rest-struts-plugin, and it use RestActionProxyFactory instead of ActionProxyFactory
I modify the code..like follow but I get a null action Proxy.. any ideas?
RestActionProxyFactory actionProxy = dispatcher.getContainer().getInstance(RestActionProxyFactory.class, “rest”);
proxy = actionProxy.createActionProxy(namespace, name, null, true, false);
Got an error with:
private static final String CONFIG_LOCATIONS = “file:WebContent/WEB-INF/applicationContext.xml”;
at
applicationContext = (new ContextLoader()).initWebApplicationContext(servletContext);
with:
Caused by: java.lang.NoSuchMethodError: javax.persistence.PersistenceContext.properties()[Ljavax/persistence/PersistenceProperty;
Can someone refer to the xml documents? is the security.xml necessary? sorry i am kinda new to this
Thx, Jorgan
You can load xml documents, but ensure you get the absolute path or relative path from the classpath to load them.
Hi,
It’s very helpful. But I’ve an problem.
I’ve an action implement Preparable. When I run the proxy.execute(), the EntityManager is opened/closed twice. This causes a problem that an entity feched in prepare() becomes detached.
Any solution?
Thanks,
For those of you who are using this base class to unit test your Struts 2 apps, have you encountered this requirement?
I have a web.xml listener placing an object in application scope using servletContext.setAttribute(foo,engine) and an interceptor expecting to locate it using actionInvocation.getStack().findValue(“#attr.foo”).
In my unit test which subclasses BaseStrutsTestCase I am putting the engine in scope using proxy.getInvocation().getStack().set(“foo”, engine), however my interceptor is finding a null when it attempts to fetch it from the stack. Is there something weird concerning the OgnlValueStack in this context?
Peace,
Scott
I was wondering if the problem with the aware interface (SessionAware) as described in comments 24 & 25 was ever resolved.
I have recently started experimenting with this very helpful unit testing code and facing same issue.
Looks like the framework isn’t setting a session object to my class implementing SessionAware. So, I call the setSession() method to set it myself. That happens before proxy.execute(), but when the time comes for proxy.execute(0 to run, it resets the session map to null.
The test passes with the option to by-pass the framework and test the action in an isolated function.
Not sure if this discussion is still active, but if anyone has any advice or solution on this issue, I would very interested in hearing it.
Many thanks.
Zarar – I modified your BaseStrutsTestCase class so that it works for testing a Struts 2 Action class that doesn’t use Spring. I’d like to publish this code along with an example of how to use it on my blog (http://www.brucephillips.name/blog). I’ve cited your name and blog article in the code comments and also will cite your orignal work in the blog article.
Is is OK with you if I publish on my blog the modified BaseStrutsTestCase class I created based on your work?
Bruce Phillips
Sure Bruce, no problem.
I am getting the following error:
java.lang.NullPointerException
at org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:104)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:178)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:348)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:253)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:123)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:167)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:105)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:83)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:207)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:74)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:127)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:107)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:206)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:115)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:143)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:121)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:170)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:123)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:50)
at gc.test.unittest.testaction.TestLoginActionUsingBaseStrutsTestCase.testInterceptorsBySettingRequestParameters(TestLoginActionUsingBaseStrutsTestCase.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:91)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
I have got the answer.
Complete BaseStrutsTestCase is like following:
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import junit.framework.TestCase;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.tiles.StrutsTilesListener;
import org.apache.struts2.views.JspSupportServlet;
import org.apache.tiles.impl.BasicTilesContainer;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextLoader;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContextEvent;
/**
* @author Arindam Ray
*/
@SuppressWarnings(“unchecked”)
public abstract class BaseStrutsTestCase extends TestCase {
private static final String CONTEXT_CONFIG_LOCATION = “/WEB-INF/applicationContext.xml,” +
“/WEB-INF/dataAccessContext.xml”;
private static final String TILES_DEFINITIONS = “/WEB-INF/tiles.xml”;
private static ApplicationContext applicationContext;
private Dispatcher dispatcher;
protected ActionProxy proxy;
protected static MockServletContext servletContext;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
public BaseStrutsTestCase(String name) {
super(name);
}
/**
* Created action class based on namespace and name
* @param clazz Class for which to create Action
* @param namespace Namespace of action
* @param name Action name
* @param parameters Request parameters
* @param session Session map
* @return Action class
* @throws Exception Catch-all exception
*/
protected Object createAction(Class clazz, String namespace, String name, Map parameters, Map session)
throws Exception {
// create a proxy class which is just a wrapper around the action call.
// The proxy is created by checking the namespace and name against the
// struts.xml configuration
proxy = dispatcher.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(namespace, name, null, true, false);
ActionContext actionContext = proxy.getInvocation().getInvocationContext();
if(parameters == null) {
// by default, don’t pass in any request parameters
actionContext.setParameters(new HashMap());
}
else {
//set the parameters
actionContext.setParameters(parameters);
}
if(session == null) {
actionContext.setSession(new HashMap());
}
else {
//set the session
actionContext.setSession(session);
}
// do not execute the result after executing the action
proxy.setExecuteResult(true);
// set the actions context to the one which the proxy is using
ServletActionContext.setContext(actionContext);
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
ServletActionContext.setRequest(request);
ServletActionContext.setResponse(response);
ServletActionContext.setServletContext(servletContext);
return proxy.getAction();
}
protected void setUp() throws Exception {
if( applicationContext == null ) {
// this is the first time so initialize Spring context
servletContext = new MockServletContext();
servletContext.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, CONTEXT_CONFIG_LOCATION);
applicationContext = (new ContextLoader()).initWebApplicationContext(servletContext);
// Struts JSP support servlet (for Freemarker)
new JspSupportServlet().init(new MockServletConfig(servletContext));
//for tiles
servletContext.addInitParameter(BasicTilesContainer.DEFINITIONS_CONFIG, TILES_DEFINITIONS);
final StrutsTilesListener tilesListener = new StrutsTilesListener();
final ServletContextEvent event = new ServletContextEvent(servletContext);
tilesListener.contextInitialized(event);
}
// Dispatcher is the guy that actually handles all requests. Pass in
// an empty. Map as the parameters but if you want to change stuff like
// what config files to read, you need to specify them here. Here’s how to
// scan packages for actions (thanks to Hardy Ferentschik – Comment 66)
// (see Dispatcher’s source code)
HashMap params = new HashMap();
params.put(“actionPackages”, “gc.action”);
dispatcher = new Dispatcher(servletContext, params);
dispatcher.init();
Dispatcher.setInstance(dispatcher);
}
}
Thanks Arsenalist for the code.
Has anybody got the above code to run by setting request parameters? The method testInterceptorsBySettingRequestParameters() doesnot work for me. There were quite few queries on this. Has anyone got it to work?
I used the approach here until I recently upgraded Struts and came up with an alternative:
http://www.digitalsanctum.com/2010/01/25/how-to-test-struts-2-actions-without-a-container/
My approach uses a combination of Struts and Spring to achieve transactional tests without the use of a container.
Thank for your post! Great work!
One question is: when I run testInterceptorsBySettingDomainObjects(), it works, but can
not invoke the interceptor. I’m using struts2+spring2+tiles
Thank You!
After a few hours of debugging I got this code to work perfectly! Thank you so much for not only posting the code, but revising it and helping with other users. This post makes it easy to set this up and troubleshoot.
A small change is needed for Struts 2.1.6. The createActionProxy() method of ActionProxyFactory needs an additional parameter for the action’s ‘method’.
To set the Action’s domain objects through request parameter, the suggested approach will not work. i.e.
request.setParameter(“id”, “123″) will not set the Id field of the action class. That has to be done in the following way –
Map params = new HashMap();
params.put(“id”, “123″);
proxy.getInvocation().getInvocationContext().setParameters(params);
how to solve this problem
There is no Action mapped for namespace / and action name createaccount. – [unknown location]
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:177)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
at net.action.StrutsTestCase.getActionProxy(StrutsTestCase.java:84)
at net.action.NewTest.testUserName(NewTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
this one is very helpful example
how to solve this problem
There is no Action mapped for namespace / and action name createaccount. – [unknown location]
at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:177)
at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
at net.action.StrutsTestCase.getActionProxy(StrutsTestCase.java:84)
at net.action.NewTest.testUserName(NewTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:46)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
There was something wrong with the usage of “assertEquals(result, “success”);”
The actual API is: assertEquals(Object expected, Object actual)
One Trackback
[...] Later on, I found a wise solution to this problem by searching and trying new possibilities. This blog was a helper for [...]