Mockito – JAXB的RETURNS_DEEP_STUBS

很抱歉没有写一段时间,但是我正忙于为DZone编写JBoss Drools Refcard,而且我正在写一本有关Mockito的书,因此我没有太多时间来写博客了……

无论如何,最近在我当前的项目中,我对使用Mockito和JAXB结构进行单元测试有一个有趣的情况。 我们已经从为我们提供的模式生成的嵌套了非常深的JAXB结构,这意味着我们无论如何都无法更改它。

让我们看一下项目结构:

project_structure

项目结构非常简单–有一个Player.xsd模式文件,该文件由于使用了jaxb2-maven-plugin生成了与目标/ jaxb /文件夹中定义的相应包中的模式相对应的生成的JAXB Java类。 pom.xml 。 说到其中,让我们看一下pom.xml文件。

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.blogspot.toomuchcoding</groupId><artifactId>mockito-deep_stubs</artifactId><version>0.0.1-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.6</maven.compiler.source><maven.compiler.target>1.6</maven.compiler.target></properties><repositories><repository><id>spring-release</id><url>http://maven.springframework.org/release</url></repository><repository><id>maven-us-nuxeo</id><url>https://maven-us.nuxeo.org/nexus/content/groups/public</url></repository></repositories><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version></dependency><dependency><groupId>org.mockito</groupId><artifactId>mockito-all</artifactId><version>1.9.5</version><scope>test</scope></dependency></dependencies><build><pluginManagement><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>2.5.1</version></plugin></plugins></pluginManagement><plugins><plugin><groupId>org.codehaus.mojo</groupId><artifactId>jaxb2-maven-plugin</artifactId><version>1.5</version><executions><execution><id>xjc</id><goals><goal>xjc</goal></goals></execution></executions><configuration><packageName>com.blogspot.toomuchcoding.model</packageName><schemaDirectory>${project.basedir}/src/main/resources/xsd</schemaDirectory></configuration></plugin></plugins></build></project>

除了先前定义的项目依赖关系外,如先前在配置节点中的jaxb2-maven-plugin中所述,您还可以基于schemaDirectory值定义packageName值,该值定义将JAXB类生成到哪个程序包,插件可以在其中找到适当的架构文件。

说到这,让我们检查一下Player.xsd模式文件( 类似于我的Spring JMS自动消息转换文章中提供的文件 ):

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"><xsd:element name="PlayerDetails"><xsd:complexType><xsd:sequence><xsd:element name="Name" type="xsd:string"/><xsd:element name="Surname" type="xsd:string"/><xsd:element name="Position" type="PositionType"/><xsd:element name="Age" type="xsd:int"/><xsd:element name="ClubDetails" type="ClubDetails"/></xsd:sequence></xsd:complexType></xsd:element><xsd:complexType name="ClubDetails"><xsd:sequence><xsd:element name="TeamName" type="xsd:string"/><xsd:element name="Country" type="CountryDetails"/></xsd:sequence></xsd:complexType><xsd:complexType name="CountryDetails"><xsd:sequence><xsd:element name="CountryName" type="xsd:string"/><xsd:element name="CountryCode" type="CountryCodeDetails"/></xsd:sequence></xsd:complexType><xsd:complexType name="CountryCodeDetails"><xsd:sequence><xsd:element name="CountryName" type="xsd:string"/><xsd:element name="CountryCode" type="CountryCodeType"/></xsd:sequence></xsd:complexType><xsd:simpleType name="CountryCodeType"><xsd:restriction base="xsd:string"><xsd:enumeration value="PL"/><xsd:enumeration value="GER"/><xsd:enumeration value="FRA"/><xsd:enumeration value="ENG"/><xsd:enumeration value="ESP"/></xsd:restriction></xsd:simpleType><xsd:simpleType name="PositionType"><xsd:restriction base="xsd:string"><xsd:enumeration value="GK"/><xsd:enumeration value="DEF"/><xsd:enumeration value="MID"/><xsd:enumeration value="ATT"/></xsd:restriction></xsd:simpleType></xsd:schema>

如您所见,我正在定义一些复杂的类型,即使它们可能没有商业意义,但您可以在现实生活中找到这样的例子。

让我们找出我们要测试的方法的外观。 在这里,我们有PlayerServiceImpl实现了PlayerService接口:

package com.blogspot.toomuchcoding.service;import com.blogspot.toomuchcoding.model.PlayerDetails;/*** User: mgrzejszczak* Date: 08.06.13* Time: 19:02*/
public class PlayerServiceImpl implements PlayerService {@Overridepublic boolean isPlayerOfGivenCountry(PlayerDetails playerDetails, String country) {String countryValue = playerDetails.getClubDetails().getCountry().getCountryCode().getCountryCode().value();return countryValue.equalsIgnoreCase(country);}
}

我们从JAXB生成的类中获取嵌套元素。 尽管它违反了Demeter的定律,但调用结构的方法却很常见,因为JAXB生成的类实际上是结构,因此,我完全同意Martin Fowler的观点,即应将其称为Demeter的建议 。 无论如何,让我们看看如何测试该方法:

@Testpublic void shouldReturnTrueIfCountryCodeIsTheSame() throws Exception {//givenPlayerDetails playerDetails = new PlayerDetails();ClubDetails clubDetails = new ClubDetails();CountryDetails countryDetails = new CountryDetails();CountryCodeDetails countryCodeDetails = new CountryCodeDetails();playerDetails.setClubDetails(clubDetails);clubDetails.setCountry(countryDetails);countryDetails.setCountryCode(countryCodeDetails);countryCodeDetails.setCountryCode(CountryCodeType.ENG);//whenboolean playerOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);//thenassertThat(playerOfGivenCountry, is(true));}

该函数检查是否具有相同的国家(地区)代码,是否从该方法中获取了一个真正的布尔值。 唯一的问题是要创建输入消息时发生的集合和实例化的数量。 在我们的项目中,嵌套元素的数量是原来的两倍,因此您只能想象创建输入对象所需的代码数量…

那么如何改善此代码呢? Mockito与Mockito.mock(…)方法的RETURN_DEEP_STUBS默认答案一起出手

@Testpublic void shouldReturnTrueIfCountryCodeIsTheSameUsingMockitoReturnDeepStubs() throws Exception {//givenPlayerDetails playerDetailsMock = mock(PlayerDetails.class, RETURNS_DEEP_STUBS);CountryCodeType countryCodeType = CountryCodeType.ENG;when(playerDetailsMock.getClubDetails().getCountry().getCountryCode().getCountryCode()).thenReturn(countryCodeType);//whenboolean playerOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetailsMock, COUNTRY_CODE_ENG);//thenassertThat(playerOfGivenCountry, is(true));}

因此,这里发生的是您使用Mockito.mock(…)方法并提供了RETURNS_DEEP_STUBS答案,该答案将为您自动创建模拟 。 请注意,不能嘲笑枚举,这就是为什么您不能在Mockito.when(…)函数playerDetailsMock.getClubDetails()。getCountry()。getCountryCode()。getCountryCode()。getValue()中编写代码的原因。

总结一下,您可以比较两个测试的可读性,并通过使用Mockito RETURNS_DEEP_STUBS默认答案来了解使用JAXB结构有多清晰。

当然,该示例的资源可从BitBucket和GitHub获得 。

参考: Mockito – JAXB的RETURNS_DEEP_STUBS,来自我们的JCG合作伙伴 Marcin Grzejszczak,位于Blog上,用于编码上瘾者博客。

翻译自: https://www.javacodegeeks.com/2013/07/mockito-returns_deep_stubs-for-jaxb.html

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

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

相关文章

Kafka#4:存储设计 分布式设计 源码分析

https://sites.google.com/a/mammatustech.com/mammatusmain/kafka-architecture/4-kafka-detailed-architecture.pdf?attredirects2&d1 https://news.ycombinator.com/item?id7386652 https://www.quora.com/Why-does-Kafka-scale-better-than-other-messaging-systems-…

协作机器人(Collaborative-Robot)安全碰撞的速度与接触力

协作机器人&#xff08;Collaborative-Robot&#xff09;的安全碰撞速度和接触力是一个非常重要的安全指标。在设计和使用协作机器人时&#xff0c;必须确保其与人类或其他物体的碰撞不会对人员造成伤害。 对于协作机器人的安全碰撞速度&#xff0c;一般会设定一个上限值&…

jackson - @JsonProperty的使用

jackson的maven依赖 <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.5.3</version> </dependency> 所以引入这一个依赖就可以了 JsonProperty 此注解用于属…

python 表达式求值数据结构_python 数据结构与算法

python 数据结构与算法1 python常见数据结构性能1.1 List1.1.1 安索引取值和赋值1.1.2 列表append和__add__()1.1.3 使用timeit模块测试执行时间1.1.4 List基本操作的大O数量级1.2 Dict1.2.1 dict数据类型2 线性结构 Linear Structure2.1 栈Stack2.1.1 抽象数据类型Stack2.1.2 …

CSS3新特性罗列

接触CSS3这么久了&#xff0c;总是到要用的时候直接拿来用&#xff0c;却没有好好地总结归纳一下&#xff0c;那就在这里好好梳理一下吧。 CSS3边框&#xff1a; 圆角边框&#xff1a; 关键&#xff1a;border-radius <!DOCTYPE html> <html> <head> <…

Log4j 2:性能接近疯狂

最近&#xff0c;Apache社区中一位受人尊敬的成员尝试了Log4j 2并在Twitter上写道&#xff1a; TheASF &#xff03;log4j2摇摇欲坠 &#xff01; 性能接近疯狂^^ http://t.co/04K6F4Xkaa — Mark Struberg&#xff08;struberg&#xff09; 2013年5月7日 &#xff08;来自M…

Uncaught SyntaxError: Invalid Unicode escape sequence异常处理

今天碰到一个问题&#xff0c;页面报错&#xff1a;Uncaught SyntaxError: Invalid Unicode escape sequence ,{index:operate,name:operate,label:<s:text name"com.vrv.cems.ptp.installSoft.operate"></s:text>,width:getPerWidth(0.1),formatter:fun…

26、jQuery

一. jQuery简介 (一) jQuery是什么&#xff1a; 是一个javascript代码仓库 是一个快速的简洁的javascript框架&#xff0c;可以简化查询DOM对象、处理事件、制作动画、处理Ajax交互过程。 (二) jQuery优势 体积小&#xff0c;使用灵巧(只需引入一个js文件)方便的选择页面元素(模…

python做自动化如何定位动态元素_python-web自动化-元素定位

# -*- coding:utf-8 -*-from selenium import webdriverfrom selenium.webdriver.common.by import By# 打开Chrome浏览器和百度网页driver webdriver.Chrome()driver.get(https://www.baidu.com/)# 元素定位&#xff1a;id绝对唯一&#xff0c;name其次# id 定位‘百度首页输…

玩转ajax

1.什么是ajax&#xff1f; Ajax 是 Asynchronous JavaScript and XML&#xff08;以及 DHTML 等&#xff09;的缩写。 2.ajax需要什么基础? HTML 用于建立 Web 表单并确定应用程序其他部分使用的字段。 JavaScript 代码是运行 Ajax 应用程序的核心代码&#xff0c;帮助改…

Spring MVC:验证器和@InitBinder

很难想象没有针对用户数据的验证逻辑的Web应用程序。 几乎所有用户的数据都有一些限制&#xff0c;例如&#xff0c;出生日期应由日&#xff0c;月&#xff0c;年等组成。SpringMVC拥有自己的数据验证解决方案&#xff0c;并且在Validator界面的帮助下可用。 Spring MVC Vali…

ADB 调试

1、adb简介 adb的全称为Android Debug Bridge&#xff0c;就是起到调试桥的作用。通过adb我们可以在Eclipse中方面通过DDMS来调试Android程序&#xff0c;说白了就是debug工具。adb的工作方式比较特殊&#xff0c;采用监听Socket TCP 5554等端口的方式让IDE和Qemu通讯&#xff…

python 函数式编程尾递归优化 day16

函数编程的特征&#xff1a; 1不可变&#xff1a;不用变量保存状态&#xff0c;不修改变量 #非函数式 a 1 def incr_test1():global a#一旦更改全局变量后后面再调用a就容易乱a 1return a incr_test1() print(a) def bar():print(from bar) def foo():print(from foo)return …

java英文试题_Java试题及答案英文版

1&#xff0e;Which two demonstrate an “is a” relationship? (Choose Two)A. public interface Person { }public class Employee extends Person { }B. public interface Shape { }public class Employee extends Sha pe { }C. public interface Color { }public class E…

margin折叠-从子元素margin-top影响父元素引出的问题

正在做一个手机端电商项目&#xff0c;顶部导航栈的布局是一个div包含一个子div&#xff0c;如果给在正常文档流中的子div一个垂直margin-top&#xff0c;神奇的现象出现了&#xff0c;两父子元素的边距没变&#xff0c;但父div跟着一起往下走了&#xff01; html代码&#xff…

js时间转换

window.οnlοadfunction(){setInterval("mytime()",1000); } function mytime(){document.getElementById("time").innerHTML fmtDate(new Date()); } function fmtDate(obj){var date new Date(obj);var y 1900date.getYear();var m "0"(…

Lambdas:来到您附近的Java 8!

什么是Lambda&#xff1f; Lambda表达式是一种匿名函数&#xff0c;可以在方法中内联编写&#xff0c;并且可以在使用表达式的任何地方使用。 有时您可能会发现它们被称为闭包&#xff0c;尽管我在下面解释了对该参考的一些注意事项。 像普通的Java方法一样&#xff0c;它具有参…

CPU-内存-IO-网络调优

一、关于CPU 中央处理器调优 1、 CPU处理方式&#xff1a; 批处理&#xff0c;顺序处理请求。(切换次数少&#xff0c;吞吐量大)分时处理。(如同"独占"&#xff0c;吞吐量小)(时间片&#xff0c;把请求分为一个一个的时间片&#xff0c;一片一片的分给CPU处理)我们现…

spark抽取mysql数据到hive_使用spark将内存中的数据写入到hive表中

使用spark将内存中的数据写入到hive表中hive-site.xmlhive.metastore.uristhrift://master:9083Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.javax.jdo.option.ConnectionURLjdbc:mysql://master:3306/metastore?createDa…

使用Merge存储引擎实现MySQL分表

使用Merge存储引擎实现MySQL分表 学习了&#xff1a;https://www.cnblogs.com/try-better-tomorrow/p/4987620.html https://www.cnblogs.com/xbq8080/p/6628034.html http://blog.csdn.net/java_bruce/article/details/71077985 https://www.cnblogs.com/johnnyzhang/articles…