Skip to content

Instantly share code, notes, and snippets.

@komiya-atsushi
Created July 4, 2014 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komiya-atsushi/470f77c73b62356633d9 to your computer and use it in GitHub Desktop.
Save komiya-atsushi/470f77c73b62356633d9 to your computer and use it in GitHub Desktop.
JSON 文字列を JUnit / hamcrest でアサーションしたいときは hamcrest-json を使うと捗る ref: http://qiita.com/komiya_atsushi/items/2a0f68b2b34e0bca5cb6
{
"foo": "bar",
"hoge": "fuga"
}
{
"hoge": "fuga",
"foo": "bar"
}
@Test
public void これではアサーションに失敗してしまう() {
String expected = "{\"foo\": \"bar\", \"hoge\": \"piyo\"}";
String actual = "{\"hoge\": \"piyo\", \"foo\": \"bar\"}";
assertThat(
actual,
is(expected));
}
package biz.k11i.demo;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs;
/**
* hamcrest-json の利用デモ。
* <p>Gradle をお使いの方なら、以下のように記述すれば OK</p>
* <pre>
* dependencies {
* testCompile group: 'junit', name: 'junit', version: '4.11'
* testCompile group: 'uk.co.datumedge', name: 'hamcrest-json', version: '0.2'
* }
* </pre>
*
* @author KOMIYA Atsushi
*/
public class HamcrestJsonDemo {
@Test
public void オブジェクト内のメンバの順序が異なっていても大丈夫() {
String expected = "{\"foo\": \"bar\", \"hoge\": \"piyo\"}";
String actual = "{\"hoge\": \"piyo\", \"foo\": \"bar\"}";
assertThat(
actual,
sameJSONAs(expected));
}
@Test
public void アサーションに失敗した場合はどこが異なるのかを明確にしてくれます() {
String expected = "{\"fuga\": \"fugafuga\"}";
String actual = "{\"hoge\": \"piyo\", \"foo\": \"bar\"}";
assertThat(
actual,
sameJSONAs(expected));
/*
* 以下の出力が得られます。
*
* Expected: "{\"fuga\": \"fugafuga\"}"
* but:
* Expected: fuga
* but none found
* ;
* Unexpected: foo
* ;
* Unexpected: hoge
*/
}
@Test
public void 余計なメンバが存在してもそれを許容する包容力も持ち合わせています() {
String expected = "{\"hoge\": \"piyo\"}";
String actual = "{\"hoge\": \"piyo\", \"foo\": \"bar\"}";
// SameJSONAs#allowingExtraUnexpectedFields() を呼び出すと、余計なメンバを許容してくれます
assertThat(
actual,
sameJSONAs(expected)
.allowingExtraUnexpectedFields());
}
@Test
public void 配列の順序を無視して比較することもできます() {
String expected = "[1, 1, 2, 3, 5, 8]";
String actual = "[8, 5, 3, 2, 1, 1]";
// SameJSONAs#allowingAnyArrayOrdering() を呼び出すと、配列の順序を無視してくれます
assertThat(
actual,
sameJSONAs(expected)
.allowingAnyArrayOrdering());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment