junit junit

这篇文章展示了如何编写JUnit测试来检查对象是否与JSON字符串匹配。 如果您要实现REST服务并想测试您的服务是否产生了预期的JSON响应,那么这非常重要。

JSONassert是比较JSON对象的有用库。 首先,您必须将Java对象转换为JSON字符串(例如,使用Jackson ),然后使用JSONassert将其与所需的JSON字符串进行比较。 (您也可以将Java对象转换为JSONObject但我发现将其转换为字符串要容易得多。)

以下代码段显示了如何使用JSONassert将对象(在这种情况下为List )与其JSON表示形式进行比较。

import org.skyscreamer.jsonassert.JSONAssert;
import com.fasterxml.jackson.databind.ObjectMapper;List<String> fruits = Arrays.asList("apple", "banana");
String fruitsJSON = new ObjectMapper().writeValueAsString(fruits);
String expectedFruitsJSON = "[\"apple\", \"banana\"]";
JSONAssert.assertEquals(expectedFruitsJSON, fruitsJSON, true);

为了简化编写此类单元测试的过程,我编写了一个名为IsEqualJSON的Hamcrest Matcher,用于比较JSON对象。 它仍然使用JSONassert,但允许您以更流畅的方式表达测试。

以下代码显示了如何使用IsEqualJSON

import static org.junit.Assert.*;
import static testutil.IsEqualJSON.*;assertThat(Arrays.asList("apple", "banana"),equalToJSON("[\"apple\", \"banana\"]"));// you can also have your expected JSON read from a file
assertThat(Arrays.asList("apple", "banana"),equalToJSONInFile("fruits.json"));

这是IsEqualJSON的代码(也在我的GitHub Repository中提供 ):

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import org.hamcrest.*;
import org.skyscreamer.jsonassert.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;/*** A Matcher for comparing JSON.* Example usage:* <pre>* assertThat(new String[] {"foo", "bar"}, equalToJSON("[\"foo\", \"bar\"]"));* assertThat(new String[] {"foo", "bar"}, equalToJSONInFile("/tmp/foo.json"));* </pre>*/
public class IsEqualJSON extends DiagnosingMatcher<Object> {private final String expectedJSON;private JSONCompareMode jsonCompareMode;public IsEqualJSON(final String expectedJSON) {this.expectedJSON = expectedJSON;this.jsonCompareMode = JSONCompareMode.STRICT;}@Overridepublic void describeTo(final Description description) {description.appendText(expectedJSON);}@Overrideprotected boolean matches(final Object actual,final Description mismatchDescription) {final String actualJSON = toJSONString(actual);final JSONCompareResult result = JSONCompare.compareJSON(expectedJSON,actualJSON,jsonCompareMode);if (!result.passed()) {mismatchDescription.appendText(result.getMessage());}return result.passed();}private static String toJSONString(final Object o) {try {return o instanceof String ?(String) o : new ObjectMapper().writeValueAsString(o);} catch (final JsonProcessingException e) {throw new RuntimeException(e);}}private static String getFileContents(final Path path) {try {return new String(Files.readAllBytes(path), StandardCharsets.UTF_8);} catch (final IOException e) {throw new RuntimeException(e);}}@Factorypublic static IsEqualJSON equalToJSON(final String expectedJSON) {return new IsEqualJSON(expectedJSON);}@Factorypublic static IsEqualJSON equalToJSONInFile(final Path expectedPath) {return equalToJSON(getFileContents(expectedPath));}@Factorypublic static IsEqualJSON equalToJSONInFile(final String expectedFileName) {return equalToJSONInFile(Paths.get(expectedFileName));}
}

翻译自: https://www.javacodegeeks.com/2018/03/junit-hamcrest-matcher-for-json.html

junit junit

junit junit_JSON的JUnit Hamcrest Matcher相关推荐

  1. JSON的JUnit Hamcrest Matcher

    这篇文章展示了如何编写JUnit测试来检查对象是否与JSON字符串匹配. 如果您要实现REST服务并想测试您的服务是否产生了预期的JSON响应,那么这一点很重要. JSONassert是比较JSON对 ...

  2. JUnit的内置Hamcrest Core Matcher支持

    在用JUnit和Hamcrest改进assertEquals的文章中,我简要讨论了Hamcrest " 核心 "匹配器与JUnit的现代版本"结合"在一起的情况 ...

  3. 在JUnit中超越核心Hamcrest

    在通过JUnit和Hamcrest改进对assertEquals的文章中,我介绍了将Hamcrest与JUnit一起使用 . 然后,我查看了JUnit的内置Hamcrest Core Matcher支 ...

  4. maven mockito_如何:测试Maven项目(JUnit,Mockito,Hamcrest,AssertJ)中的依赖项

    maven mockito 对于当今的大多数Java项目而言,JUnit本身还远远不够. 您还需要一个模拟库,也许还有其他东西. 在此迷你操作指南中,我介绍了可以在新的Java项目中开始的测试依赖项. ...

  5. 如何:在Maven项目(JUnit,Mockito,Hamcrest,AssertJ)中测试依赖项

    对于当今的大多数Java项目,JUnit本身还远远不够. 您还需要一个模拟库,也许还有其他东西. 在此迷你操作指南中,我介绍了可以在新的Java项目中开始的测试依赖项. 一切都始于JUnit Mave ...

  6. junit rule_使用JUnit的ExpectedException和@Rule测试自定义异常

    junit rule 异常测试 为什么要测试异常流? 就像所有代码一样,测试覆盖率在代码和应该产生的业务功能之间写了一个合同,从而为您提供了代码的有效文档 ,以及可以尽早且经常强调功能的附加功能. 我 ...

  7. junit:junit_处理JUnit中异常的另一种方法:catch-exception

    junit:junit JUnit中有许多处理异常的方法 (JUnit中有3种处理异常的方法.选择哪一种? JUnit ExpectedException规则:超越了基础 ). 在这篇文章中,我将介绍 ...

  8. JUnit 5 –下一代JUnit的初步了解

    2月初, JUnit 5(又名JUnit Lambda)团队发布了一个alpha版本. 由于JUnit 4是我工具箱中使用最频繁的项目之一,因此我认为值得一看下一个主要版本. 我试用了最新版本,并记下 ...

  9. junit junit_穿越JUnit流

    junit junit 关于JUnit 5迁移的好处之一是,您可以在老式模式下运行JUnit 4测试,并且所有内容仍然兼容. 不利的一面是,某些注释和方法在JUnit 4和JUnit 5中具有相同的名 ...

最新文章

  1. Annotation
  2. Servlet的Filter的使用
  3. .net 导出excel和word
  4. SAP实施项目中顾问与客户的有效沟通
  5. python内置序列类型_Python序列内置类型之元组类型详解
  6. Android横向ListView功能实现
  7. 列表是不是python数据类型的是_在Python中,一个列表中的数据类型是否可以不相同?(回答可以or不可以)...
  8. 用 DocFetcher 全文搜索
  9. linux stm32 虚拟串口驱动安装,stm32usb虚拟串口驱动
  10. 关于kafka中ISR、AR、HW、LEO、LSO、LW的含义详解
  11. 哆啦A梦的神奇口袋 - 这全是宝藏
  12. Excel 提取单元格中的数字、中/英文方法
  13. 甲骨文裁员是在为云业务转型太慢埋单
  14. 淘宝逛逛ODL模型优化总结
  15. delphi android 蓝牙,Android实例-Delphi开发蓝牙官方实例解析(XE10+小米2+小米5)
  16. 选择婚庆公司的注意事项
  17. 机器视觉——视觉工程师需要知道的知识
  18. 解读人工智能的2021:回顾那些激动人心的重大突破
  19. 用变量定义数组的几个方法
  20. 青少年CTF_misc部分题解

热门文章

  1. [ZJOI2014] 星系调查(树上差分 + 数学推式子)
  2. 数据结构之基环树——骑士,Island,旅行加强版,Number of Simple Paths,Traffic Network in Numazu,Card Game
  3. jzoj4800-[GDOI2017模拟9.24]周末晚会【dp,循环重构】
  4. 欢乐纪中某B组赛【2018.12.15】
  5. 【jzoj】2018.2.5NOIP普及组——C组模拟赛
  6. 【DP】合唱队形(jzoj 1122)
  7. Linux运维常用检查网络工具
  8. Oracle入门(三B)之11G新特性 SYSASM 角色用来管理ASM
  9. 你真的以为你了解Java的序列化了吗
  10. List转数组toArray方法