diff --git a/build.gradle b/build.gradle index 512fe344..abdd9e3a 100644 --- a/build.gradle +++ b/build.gradle @@ -70,6 +70,7 @@ subprojects { dependency 'junit:junit:4.12' dependency 'io.rest-assured:rest-assured:3.0.7' dependency 'org.apache.pdfbox:pdfbox:2.0.7' + dependency 'org.assertj:assertj-core:2.9.1' dependency 'org.asciidoctor:asciidoctorj:1.5.6' dependency 'org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.16' dependency 'org.hamcrest:hamcrest-core:1.3' diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 08722da0..0eab6766 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -73,7 +73,7 @@ + value="io.restassured.RestAssured.*, org.assertj.core.api.Assertions.*, org.hamcrest.CoreMatchers.*, org.hamcrest.Matchers.*, org.mockito.Mockito.*, org.mockito.BDDMockito.*, org.mockito.Matchers.*, org.springframework.restdocs.cli.CliDocumentation.*, org.springframework.restdocs.headers.HeaderDocumentation.*, org.springframework.restdocs.hypermedia.HypermediaDocumentation.*, org.springframework.restdocs.mockmvc.IterableEnumeration.*, org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*, org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.*, org.springframework.restdocs.payload.PayloadDocumentation.*, org.springframework.restdocs.operation.preprocess.Preprocessors.*, org.springframework.restdocs.request.RequestDocumentation.*, org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.*, org.springframework.restdocs.restassured3.operation.preprocess.RestAssuredPreprocessors.*, org.springframework.restdocs.snippet.Attributes.*, org.springframework.restdocs.templates.TemplateFormats.*, org.springframework.restdocs.test.SnippetConditions.*, org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.*, org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*, org.springframework.test.web.servlet.result.MockMvcResultMatchers.*, org.springframework.web.reactive.function.BodyInserters.*, org.springframework.web.reactive.function.server.RequestPredicates.GET, org.springframework.web.reactive.function.server.RequestPredicates.POST" /> diff --git a/samples/rest-notes-spring-hateoas/build.gradle b/samples/rest-notes-spring-hateoas/build.gradle index c6ebe136..112fb41e 100644 --- a/samples/rest-notes-spring-hateoas/build.gradle +++ b/samples/rest-notes-spring-hateoas/build.gradle @@ -43,6 +43,7 @@ dependencies { runtime 'org.atteo:evo-inflector:1.2.1' testCompile 'com.jayway.jsonpath:json-path' + testCompile 'org.assertj:assertj-core' testCompile 'org.springframework.boot:spring-boot-starter-test' testCompile 'org.springframework.restdocs:spring-restdocs-mockmvc' } diff --git a/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/NullOrNotBlankTests.java b/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/NullOrNotBlankTests.java index 24d9e85a..d7e9e309 100644 --- a/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/NullOrNotBlankTests.java +++ b/samples/rest-notes-spring-hateoas/src/test/java/com/example/notes/NullOrNotBlankTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,7 @@ package com.example.notes; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Set; @@ -35,25 +34,25 @@ public class NullOrNotBlankTests { @Test public void nullValue() { Set> violations = validator.validate(new Constrained(null)); - assertThat(violations.size(), is(0)); + assertThat(violations).isEmpty(); } @Test public void zeroLengthValue() { Set> violations = validator.validate(new Constrained("")); - assertThat(violations.size(), is(2)); + assertThat(violations).hasSize(2); } @Test public void blankValue() { Set> violations = validator.validate(new Constrained(" ")); - assertThat(violations.size(), is(2)); + assertThat(violations).hasSize(2); } @Test public void nonBlankValue() { Set> violations = validator.validate(new Constrained("test")); - assertThat(violations.size(), is(0)); + assertThat(violations).isEmpty(); } static class Constrained { diff --git a/spring-restdocs-asciidoctor/build.gradle b/spring-restdocs-asciidoctor/build.gradle index 51352428..dcb58c2f 100644 --- a/spring-restdocs-asciidoctor/build.gradle +++ b/spring-restdocs-asciidoctor/build.gradle @@ -5,6 +5,7 @@ dependencies { testCompile 'junit:junit' testCompile 'org.apache.pdfbox:pdfbox' testCompile 'org.asciidoctor:asciidoctorj' + testCompile 'org.assertj:assertj-core' testCompile 'org.springframework:spring-core' testRuntime 'org.asciidoctor:asciidoctorj-pdf' } \ No newline at end of file diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessorTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessorTests.java index 83ef4782..47f02134 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessorTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/DefaultAttributesPreprocessorTests.java @@ -23,8 +23,7 @@ import org.asciidoctor.Attributes; import org.asciidoctor.Options; import org.junit.Test; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DefaultAttributesPreprocessor}. @@ -38,8 +37,8 @@ public class DefaultAttributesPreprocessorTests { Options options = new Options(); options.setAttributes(new Attributes("projectdir=../../..")); String converted = Asciidoctor.Factory.create().convert("{snippets}", options); - assertThat(converted, - containsString("build" + File.separatorChar + "generated-snippets")); + assertThat(converted) + .contains("build" + File.separatorChar + "generated-snippets"); } @Test @@ -47,7 +46,7 @@ public class DefaultAttributesPreprocessorTests { Options options = new Options(); options.setAttributes(new Attributes("snippets=custom projectdir=../../..")); String converted = Asciidoctor.Factory.create().convert("{snippets}", options); - assertThat(converted, containsString("custom")); + assertThat(converted).contains("custom"); } @Test @@ -56,7 +55,7 @@ public class DefaultAttributesPreprocessorTests { options.setAttributes(new Attributes("projectdir=../../..")); String converted = Asciidoctor.Factory.create() .convert(":snippets: custom\n{snippets}", options); - assertThat(converted, containsString("custom")); + assertThat(converted).contains("custom"); } } diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/OperationBlockMacroTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/OperationBlockMacroTests.java index b3973157..bacfc222 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/OperationBlockMacroTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/OperationBlockMacroTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,10 +39,7 @@ import org.junit.Test; import org.springframework.util.FileSystemUtils; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for Ruby operation block macro. @@ -73,7 +70,7 @@ public class OperationBlockMacroTests { public void codeBlockSnippetInclude() throws Exception { String result = this.asciidoctor.convert( "operation::some-operation[snippets='curl-request']", this.options); - assertThat(result, equalTo(getExpectedContentFromFile("snippet-simple"))); + assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-simple")); } @Test @@ -83,7 +80,7 @@ public class OperationBlockMacroTests { this.options.setAttributes(attributes); String result = this.asciidoctor.convert( "operation::{name}-operation[snippets='curl-request']", this.options); - assertThat(result, equalTo(getExpectedContentFromFile("snippet-simple"))); + assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-simple")); } @Test @@ -91,15 +88,15 @@ public class OperationBlockMacroTests { File output = configurePdfOutput(); this.asciidoctor.convert("operation::some-operation[snippets='curl-request']", this.options); - assertThat(extractStrings(output), - hasItems("Curl request", "$ curl 'http://localhost:8080/' -i", "1")); + assertThat(extractStrings(output)).containsExactly("Curl request", + "$ curl 'http://localhost:8080/' -i", "1"); } @Test public void tableSnippetInclude() throws Exception { String result = this.asciidoctor.convert( "operation::some-operation[snippets='response-fields']", this.options); - assertThat(result, equalTo(getExpectedContentFromFile("snippet-table"))); + assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-table")); } @Test @@ -107,9 +104,9 @@ public class OperationBlockMacroTests { File output = configurePdfOutput(); this.asciidoctor.convert("operation::some-operation[snippets='response-fields']", this.options); - assertThat(extractStrings(output), - hasItems("Response fields", "Path", "Type", "Description", "a", "Object", - "one", "a.b", "Number", "two", "a.c", "String", "three", "1")); + assertThat(extractStrings(output)).containsExactly("Response fields", "Path", + "Type", "Description", "a", "Object", "one", "a.b", "Number", "two", + "a.c", "String", "three", "1"); } @Test @@ -117,7 +114,7 @@ public class OperationBlockMacroTests { String result = this.asciidoctor.convert( "== Section\n" + "operation::some-operation[snippets='curl-request']", this.options); - assertThat(result, equalTo(getExpectedContentFromFile("snippet-in-section"))); + assertThat(result).isEqualTo(getExpectedContentFromFile("snippet-in-section")); } @Test @@ -126,8 +123,8 @@ public class OperationBlockMacroTests { this.asciidoctor.convert( "== Section\n" + "operation::some-operation[snippets='curl-request']", this.options); - assertThat(extractStrings(output), hasItems("Section", "Curl request", - "$ curl 'http://localhost:8080/' -i", "1")); + assertThat(extractStrings(output)).containsExactly("Section", "Curl request", + "$ curl 'http://localhost:8080/' -i", "1"); } @Test @@ -135,43 +132,43 @@ public class OperationBlockMacroTests { String result = this.asciidoctor.convert( "operation::some-operation[snippets='curl-request,http-request']", this.options); - assertThat(result, equalTo(getExpectedContentFromFile("multiple-snippets"))); + assertThat(result).isEqualTo(getExpectedContentFromFile("multiple-snippets")); } @Test public void useMacroWithoutSnippetAttributeAddsAllSnippets() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[]", this.options); - assertThat(result, equalTo(getExpectedContentFromFile("all-snippets"))); + assertThat(result).isEqualTo(getExpectedContentFromFile("all-snippets")); } @Test public void useMacroWithEmptySnippetAttributeAddsAllSnippets() throws Exception { String result = this.asciidoctor.convert("operation::some-operation[snippets=]", this.options); - assertThat(result, equalTo(getExpectedContentFromFile("all-snippets"))); + assertThat(result).isEqualTo(getExpectedContentFromFile("all-snippets")); } @Test public void includingMissingSnippetAddsWarning() throws Exception { String result = this.asciidoctor.convert( "operation::some-operation[snippets='missing-snippet']", this.options); - assertThat(result, startsWith(getExpectedContentFromFile("missing-snippet"))); + assertThat(result).startsWith(getExpectedContentFromFile("missing-snippet")); } @Test public void defaultTitleIsProvidedForCustomSnippet() throws Exception { String result = this.asciidoctor.convert( "operation::some-operation[snippets='custom-snippet']", this.options); - assertThat(result, - equalTo(getExpectedContentFromFile("custom-snippet-default-title"))); + assertThat(result) + .isEqualTo(getExpectedContentFromFile("custom-snippet-default-title")); } @Test public void missingOperationIsHandledGracefully() throws Exception { String result = this.asciidoctor.convert("operation::missing-operation[]", this.options); - assertThat(result, startsWith(getExpectedContentFromFile("missing-operation"))); + assertThat(result).startsWith(getExpectedContentFromFile("missing-operation")); } @Test @@ -181,8 +178,8 @@ public class OperationBlockMacroTests { ":operation-curl-request-title: Example request\n" + "operation::some-operation[snippets='curl-request']", this.options); - assertThat(result, - equalTo(getExpectedContentFromFile("built-in-snippet-custom-title"))); + assertThat(result) + .isEqualTo(getExpectedContentFromFile("built-in-snippet-custom-title")); } @Test @@ -192,8 +189,8 @@ public class OperationBlockMacroTests { ":operation-custom-snippet-title: Customized title\n" + "operation::some-operation[snippets='custom-snippet']", this.options); - assertThat(result, - equalTo(getExpectedContentFromFile("custom-snippet-custom-title"))); + assertThat(result) + .isEqualTo(getExpectedContentFromFile("custom-snippet-custom-title")); } private String getExpectedContentFromFile(String fileName) @@ -226,7 +223,7 @@ public class OperationBlockMacroTests { private List extractStrings(File pdfFile) throws IOException { PDDocument pdf = PDDocument.load(pdfFile); - assertThat(pdf.getNumberOfPages(), equalTo(1)); + assertThat(pdf.getNumberOfPages()).isEqualTo(1); StringExtractor stringExtractor = new StringExtractor(); stringExtractor.processPage(pdf.getPage(0)); return stringExtractor.getStrings(); diff --git a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java index 74bbda7e..711408be 100644 --- a/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java +++ b/spring-restdocs-asciidoctor/src/test/java/org/springframework/restdocs/asciidoctor/SnippetsDirectoryResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,9 +26,8 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; /** * Tests for {@link SnippetsDirectoryResolver}. @@ -52,9 +51,9 @@ public class SnippetsDirectoryResolverTests { new File(this.temporaryFolder.getRoot(), "src/main/asciidoc") .getAbsolutePath()); File snippetsDirectory = getMavenSnippetsDirectory(attributes); - assertThat(snippetsDirectory.isAbsolute(), is(false)); - assertThat(snippetsDirectory, - equalTo(new File("../../../target/generated-snippets"))); + assertThat(snippetsDirectory).isRelative(); + assertThat(snippetsDirectory) + .isEqualTo(new File("../../../target/generated-snippets")); } @Test @@ -85,8 +84,8 @@ public class SnippetsDirectoryResolverTests { attributes.put("projectdir", "project/dir"); File snippetsDirectory = new SnippetsDirectoryResolver() .getSnippetsDirectory(attributes); - assertThat(snippetsDirectory, - equalTo(new File("project/dir/build/generated-snippets"))); + assertThat(snippetsDirectory) + .isEqualTo(new File("project/dir/build/generated-snippets")); } @Test diff --git a/spring-restdocs-core/build.gradle b/spring-restdocs-core/build.gradle index 47aa151b..186b3405 100644 --- a/spring-restdocs-core/build.gradle +++ b/spring-restdocs-core/build.gradle @@ -35,6 +35,7 @@ dependencies { optional 'junit:junit' optional 'org.hibernate.validator:hibernate-validator' optional 'org.junit.jupiter:junit-jupiter-api' + testCompile 'org.assertj:assertj-core' testCompile 'org.javamoney:moneta' testCompile 'org.mockito:mockito-core' testCompile 'org.hamcrest:hamcrest-core' diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java index 014caa4d..11b51651 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/AbstractSnippetTests.java @@ -27,13 +27,13 @@ import org.junit.runners.Parameterized.Parameters; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpStatus; import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.test.ExpectedSnippets; +import org.springframework.restdocs.test.GeneratedSnippets; import org.springframework.restdocs.test.OperationBuilder; -import org.springframework.restdocs.test.SnippetMatchers; -import org.springframework.restdocs.test.SnippetMatchers.CodeBlockMatcher; -import org.springframework.restdocs.test.SnippetMatchers.HttpRequestMatcher; -import org.springframework.restdocs.test.SnippetMatchers.HttpResponseMatcher; -import org.springframework.restdocs.test.SnippetMatchers.TableMatcher; +import org.springframework.restdocs.test.SnippetConditions; +import org.springframework.restdocs.test.SnippetConditions.CodeBlockCondition; +import org.springframework.restdocs.test.SnippetConditions.HttpRequestCondition; +import org.springframework.restdocs.test.SnippetConditions.HttpResponseCondition; +import org.springframework.restdocs.test.SnippetConditions.TableCondition; import org.springframework.web.bind.annotation.RequestMethod; import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor; @@ -50,7 +50,7 @@ public abstract class AbstractSnippetTests { protected final TemplateFormat templateFormat; @Rule - public ExpectedSnippets snippets; + public GeneratedSnippets generatedSnippets; @Rule public OperationBuilder operationBuilder; @@ -62,34 +62,34 @@ public abstract class AbstractSnippetTests { } public AbstractSnippetTests(String name, TemplateFormat templateFormat) { - this.snippets = new ExpectedSnippets(templateFormat); + this.generatedSnippets = new GeneratedSnippets(templateFormat); this.templateFormat = templateFormat; this.operationBuilder = new OperationBuilder(this.templateFormat); } - public CodeBlockMatcher codeBlock(String language) { + public CodeBlockCondition codeBlock(String language) { return this.codeBlock(language, null); } - public CodeBlockMatcher codeBlock(String language, String options) { - return SnippetMatchers.codeBlock(this.templateFormat, language, options); + public CodeBlockCondition codeBlock(String language, String options) { + return SnippetConditions.codeBlock(this.templateFormat, language, options); } - public TableMatcher tableWithHeader(String... headers) { - return SnippetMatchers.tableWithHeader(this.templateFormat, headers); + public TableCondition tableWithHeader(String... headers) { + return SnippetConditions.tableWithHeader(this.templateFormat, headers); } - public TableMatcher tableWithTitleAndHeader(String title, String... headers) { - return SnippetMatchers.tableWithTitleAndHeader(this.templateFormat, title, + public TableCondition tableWithTitleAndHeader(String title, String... headers) { + return SnippetConditions.tableWithTitleAndHeader(this.templateFormat, title, headers); } - public HttpRequestMatcher httpRequest(RequestMethod method, String uri) { - return SnippetMatchers.httpRequest(this.templateFormat, method, uri); + public HttpRequestCondition httpRequest(RequestMethod method, String uri) { + return SnippetConditions.httpRequest(this.templateFormat, method, uri); } - public HttpResponseMatcher httpResponse(HttpStatus responseStatus) { - return SnippetMatchers.httpResponse(this.templateFormat, responseStatus); + public HttpResponseCondition httpResponse(HttpStatus responseStatus) { + return SnippetConditions.httpResponse(this.templateFormat, responseStatus); } protected FileSystemResource snippetResource(String name) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java index 7843d3d0..0f3b453c 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/RestDocumentationGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,9 +42,7 @@ import org.springframework.restdocs.operation.preprocess.OperationResponsePrepro import org.springframework.restdocs.operation.preprocess.Preprocessors; import org.springframework.restdocs.snippet.Snippet; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -206,10 +204,9 @@ public class RestDocumentationGeneratorTests { throws IOException { ArgumentCaptor operation = ArgumentCaptor.forClass(Operation.class); verify(snippet).document(operation.capture()); - assertThat(this.operationRequest, is(equalTo(operation.getValue().getRequest()))); - assertThat(this.operationResponse, - is(equalTo(operation.getValue().getResponse()))); - assertThat(attributes, is(equalTo(operation.getValue().getAttributes()))); + assertThat(this.operationRequest).isEqualTo(operation.getValue().getRequest()); + assertThat(this.operationResponse).isEqualTo(operation.getValue().getResponse()); + assertThat(attributes).isEqualTo(operation.getValue().getAttributes()); } private void verifySnippetInvocation(Snippet snippet, @@ -217,18 +214,17 @@ public class RestDocumentationGeneratorTests { Map attributes, int times) throws IOException { ArgumentCaptor operation = ArgumentCaptor.forClass(Operation.class); verify(snippet, Mockito.times(times)).document(operation.capture()); - assertThat(operationRequest, is(equalTo(operation.getValue().getRequest()))); - assertThat(operationResponse, is(equalTo(operation.getValue().getResponse()))); + assertThat(operationRequest).isEqualTo(operation.getValue().getRequest()); + assertThat(operationResponse).isEqualTo(operation.getValue().getResponse()); } private void verifySnippetInvocation(InOrder inOrder, Snippet snippet, Map attributes) throws IOException { ArgumentCaptor operation = ArgumentCaptor.forClass(Operation.class); inOrder.verify(snippet).document(operation.capture()); - assertThat(this.operationRequest, is(equalTo(operation.getValue().getRequest()))); - assertThat(this.operationResponse, - is(equalTo(operation.getValue().getResponse()))); - assertThat(attributes, is(equalTo(operation.getValue().getAttributes()))); + assertThat(this.operationRequest).isEqualTo(operation.getValue().getRequest()); + assertThat(this.operationResponse).isEqualTo(operation.getValue().getResponse()); + assertThat(attributes).isEqualTo(operation.getValue().getAttributes()); } private static OperationRequest createRequest() { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java index fe5fe13a..e9d00524 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/ConcatenatingCommandFormatterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,7 @@ import java.util.Collections; import org.junit.Test; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CommandFormatter}. @@ -37,25 +35,25 @@ public class ConcatenatingCommandFormatterTests { @Test public void formattingAnEmptyListProducesAnEmptyString() { - assertThat(this.singleLineFormat.format(Collections.emptyList()), - is(equalTo(""))); + assertThat(this.singleLineFormat.format(Collections.emptyList())) + .isEqualTo(""); } @Test public void formattingNullProducesAnEmptyString() { - assertThat(this.singleLineFormat.format(null), is(equalTo(""))); + assertThat(this.singleLineFormat.format(null)).isEqualTo(""); } @Test public void formattingASingleElement() { - assertThat(this.singleLineFormat.format(Collections.singletonList("alpha")), - is(equalTo(" alpha"))); + assertThat(this.singleLineFormat.format(Collections.singletonList("alpha"))) + .isEqualTo(" alpha"); } @Test public void formattingMultipleElements() { - assertThat(this.singleLineFormat.format(Arrays.asList("alpha", "bravo")), - is(equalTo(String.format(" alpha bravo")))); + assertThat(this.singleLineFormat.format(Arrays.asList("alpha", "bravo"))) + .isEqualTo(String.format(" alpha bravo")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java index 32507e3a..6589c4a8 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/CurlRequestSnippetTests.java @@ -25,17 +25,10 @@ import org.junit.runners.Parameterized; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; import org.springframework.util.Base64Utils; -import static org.hamcrest.CoreMatchers.containsString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.springframework.restdocs.snippet.Attributes.attributes; -import static org.springframework.restdocs.snippet.Attributes.key; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CurlRequestSnippet}. @@ -58,344 +51,325 @@ public class CurlRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequest() throws IOException { - this.snippets.expectCurlRequest().withContents( - codeBlock("bash").content("$ curl 'http://localhost/foo' -i -X GET")); new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo").build()); + assertThat(this.generatedSnippets.curlRequest()).is( + codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET")); } @Test public void getRequestWithParameter() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?a=alpha' -i -X GET")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").param("a", "alpha").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?a=alpha' -i -X GET")); } @Test public void nonGetRequest() throws IOException { - this.snippets.expectCurlRequest().withContents( - codeBlock("bash").content("$ curl 'http://localhost/foo' -i -X POST")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("POST").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo' -i -X POST")); } @Test public void requestWithContent() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo' -i -X GET -d 'content'")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").content("content").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo' -i -X GET -d 'content'")); } @Test public void getRequestWithQueryString() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?param=value' -i -X GET")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo?param=value").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?param=value' -i -X GET")); } @Test public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?param=value' -i -X GET")); new CurlRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo?param=value") .param("param", "value").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?param=value' -i -X GET")); } @Test public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo?a=alpha") .param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); } @Test public void getRequestWithDisjointQueryStringAndParameters() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo?a=alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X GET")); } @Test public void getRequestWithQueryStringWithNoValue() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?param' -i -X GET")); new CurlRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo?param").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?param' -i -X GET")); } @Test public void postRequestWithQueryString() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?param=value' -i -X POST")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo?param=value").method("POST").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?param=value' -i -X POST")); } @Test public void postRequestWithQueryStringWithNoValue() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?param' -i -X POST")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo?param").method("POST").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?param' -i -X POST")); } @Test public void postRequestWithOneParameter() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo") .method("POST").param("k1", "v1").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=v1'")); } @Test public void postRequestWithOneParameterWithNoValue() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo' -i -X POST -d 'k1='")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("POST").param("k1").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1='")); } @Test public void postRequestWithMultipleParameters() throws IOException { - this.snippets.expectCurlRequest().withContents( - codeBlock("bash").content("$ curl 'http://localhost/foo' -i -X POST" - + " -d 'k1=v1&k1=v1-bis&k2=v2'")); new CurlRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo").method("POST") .param("k1", "v1", "v1-bis").param("k2", "v2").build()); + assertThat(this.generatedSnippets.curlRequest()).is( + codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST" + + " -d 'k1=v1&k1=v1-bis&k2=v2'")); } @Test public void postRequestWithUrlEncodedParameter() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'")); new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo") .method("POST").param("k1", "a&b").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo' -i -X POST -d 'k1=a%26b'")); } @Test public void postRequestWithDisjointQueryStringAndParameter() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash").content( - "$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo?a=alpha") .method("POST").param("b", "bravo").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent( + "$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); } @Test public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST")); new CurlRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") .method("POST").param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i -X POST")); } @Test public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash").content( - "$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo?a=alpha") .method("POST").param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent( + "$ curl 'http://localhost/foo?a=alpha' -i -X POST -d 'b=bravo'")); } @Test public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { - this.snippets.expectCurlRequest().withContents( - codeBlock("bash").content("$ curl 'http://localhost/foo' -i -X POST " - + "-H 'Content-Type: application/x-www-form-urlencoded' " - + "-d 'a=alpha&b=bravo'")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("POST").content("a=alpha&b=bravo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.curlRequest()).is( + codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X POST " + + "-H 'Content-Type: application/x-www-form-urlencoded' " + + "-d 'a=alpha&b=bravo'")); } @Test public void putRequestWithOneParameter() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("PUT").param("k1", "v1").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=v1'")); } @Test public void putRequestWithMultipleParameters() throws IOException { - this.snippets.expectCurlRequest().withContents( - codeBlock("bash").content("$ curl 'http://localhost/foo' -i -X PUT" - + " -d 'k1=v1&k1=v1-bis&k2=v2'")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("PUT").param("k1", "v1") .param("k1", "v1-bis").param("k2", "v2").build()); + assertThat(this.generatedSnippets.curlRequest()).is( + codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X PUT" + + " -d 'k1=v1&k1=v1-bis&k2=v2'")); } @Test public void putRequestWithUrlEncodedParameter() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'")); new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo") .method("PUT").param("k1", "a&b").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo' -i -X PUT -d 'k1=a%26b'")); } @Test public void requestWithHeaders() throws IOException { - this.snippets.expectCurlRequest().withContents( - codeBlock("bash").content("$ curl 'http://localhost/foo' -i -X GET" - + " -H 'Content-Type: application/json' -H 'a: alpha'")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha").build()); + assertThat(this.generatedSnippets.curlRequest()).is( + codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET" + + " -H 'Content-Type: application/json' -H 'a: alpha'")); } @Test public void requestWithHeadersMultiline() throws IOException { - this.snippets.expectCurlRequest() - .withContents(codeBlock("bash").content( - String.format("$ curl 'http://localhost/foo' -i -X GET \\%n" - + " -H 'Content-Type: application/json' \\%n" - + " -H 'a: alpha'"))); new CurlRequestSnippet(CliDocumentation.multiLineFormat()) .document(this.operationBuilder.request("http://localhost/foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent(String.format("$ curl 'http://localhost/foo' -i -X GET \\%n" + + " -H 'Content-Type: application/json' \\%n" + + " -H 'a: alpha'"))); } @Test public void requestWithCookies() throws IOException { - this.snippets.expectCurlRequest().withContents( - codeBlock("bash").content("$ curl 'http://localhost/foo' -i -X GET" - + " --cookie 'name1=value1;name2=value2'")); new CurlRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo") .cookie("name1", "value1").cookie("name2", "value2").build()); + assertThat(this.generatedSnippets.curlRequest()).is( + codeBlock("bash").withContent("$ curl 'http://localhost/foo' -i -X GET" + + " --cookie 'name1=value1;name2=value2'")); } @Test public void multipartPostWithNoSubmittedFileName() throws IOException { - String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " - + "'Content-Type: multipart/form-data' -F " - + "'metadata={\"description\": \"foo\"}'"; - this.snippets.expectCurlRequest() - .withContents(codeBlock("bash").content(expectedContent)); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("metadata", "{\"description\": \"foo\"}".getBytes()).build()); + String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + + "'Content-Type: multipart/form-data' -F " + + "'metadata={\"description\": \"foo\"}'"; + assertThat(this.generatedSnippets.curlRequest()) + .is(codeBlock("bash").withContent(expectedContent)); } @Test public void multipartPostWithContentType() throws IOException { - String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " - + "'Content-Type: multipart/form-data' -F " - + "'image=@documents/images/example.png;type=image/png'"; - this.snippets.expectCurlRequest() - .withContents(codeBlock("bash").content(expectedContent)); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", new byte[0]) .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) .submittedFileName("documents/images/example.png").build()); + String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + + "'Content-Type: multipart/form-data' -F " + + "'image=@documents/images/example.png;type=image/png'"; + assertThat(this.generatedSnippets.curlRequest()) + .is(codeBlock("bash").withContent(expectedContent)); } @Test public void multipartPost() throws IOException { - String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " - + "'Content-Type: multipart/form-data' -F " - + "'image=@documents/images/example.png'"; - this.snippets.expectCurlRequest() - .withContents(codeBlock("bash").content(expectedContent)); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", new byte[0]) .submittedFileName("documents/images/example.png").build()); + String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + + "'Content-Type: multipart/form-data' -F " + + "'image=@documents/images/example.png'"; + assertThat(this.generatedSnippets.curlRequest()) + .is(codeBlock("bash").withContent(expectedContent)); } @Test public void multipartPostWithParameters() throws IOException { - String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " - + "'Content-Type: multipart/form-data' -F " - + "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' " - + "-F 'b=banana'"; - this.snippets.expectCurlRequest() - .withContents(codeBlock("bash").content(expectedContent)); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", new byte[0]) .submittedFileName("documents/images/example.png").and() .param("a", "apple", "avocado").param("b", "banana").build()); + String expectedContent = "$ curl 'http://localhost/upload' -i -X POST -H " + + "'Content-Type: multipart/form-data' -F " + + "'image=@documents/images/example.png' -F 'a=apple' -F 'a=avocado' " + + "-F 'b=banana'"; + assertThat(this.generatedSnippets.curlRequest()) + .is(codeBlock("bash").withContent(expectedContent)); } @Test public void basicAuthCredentialsAreSuppliedUsingUserOption() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo") .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) .build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo' -i -u 'user:secret' -X GET")); } @Test public void customAttributes() throws IOException { - this.snippets.expectCurlRequest() - .withContents(containsString("curl request title")); - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("curl-request")) - .willReturn(snippetResource("curl-request-with-title")); - new CurlRequestSnippet( - attributes( - key("title").value("curl request title")), - this.commandFormatter) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)) - .request("http://localhost/foo").build()); - } - - @Test - public void customHostHeaderIsIncluded() throws IOException { - this.snippets.expectCurlRequest().withContents(codeBlock("bash").content( - "$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'" - + " -H 'Content-Type: application/json' -H 'a: alpha'")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo") .header(HttpHeaders.HOST, "api.example.com") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash").withContent( + "$ curl 'http://localhost/foo' -i -X GET -H 'Host: api.example.com'" + + " -H 'Content-Type: application/json' -H 'a: alpha'")); } @Test public void postWithContentAndParameters() throws IOException { - this.snippets.expectCurlRequest() - .withContents(codeBlock("bash") - .content("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " - + "-X POST -d 'Some content'")); new CurlRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").param("a", "alpha").method("POST") .param("b", "bravo").content("Some content").build()); + assertThat(this.generatedSnippets.curlRequest()).is(codeBlock("bash") + .withContent("$ curl 'http://localhost/foo?a=alpha&b=bravo' -i " + + "-X POST -d 'Some content'")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java index 48bcf8ba..6a7d2685 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/cli/HttpieRequestSnippetTests.java @@ -25,17 +25,10 @@ import org.junit.runners.Parameterized; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.AbstractSnippetTests; -import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateResourceResolver; -import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; import org.springframework.util.Base64Utils; -import static org.hamcrest.CoreMatchers.containsString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.springframework.restdocs.snippet.Attributes.attributes; -import static org.springframework.restdocs.snippet.Attributes.key; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HttpieRequestSnippet}. @@ -59,339 +52,323 @@ public class HttpieRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequest() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http GET 'http://localhost/foo'")); new HttpieRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'")); } @Test public void getRequestWithParameter() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http GET 'http://localhost/foo?a=alpha'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").param("a", "alpha").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http GET 'http://localhost/foo?a=alpha'")); } @Test public void nonGetRequest() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http POST 'http://localhost/foo'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("POST").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent("$ http POST 'http://localhost/foo'")); } @Test public void requestWithContent() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ echo 'content' | http GET 'http://localhost/foo'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").content("content").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ echo 'content' | http GET 'http://localhost/foo'")); } @Test public void getRequestWithQueryString() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http GET 'http://localhost/foo?param=value'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo?param=value").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http GET 'http://localhost/foo?param=value'")); } @Test public void getRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http GET 'http://localhost/foo?param=value'")); new HttpieRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo?param=value") .param("param", "value").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http GET 'http://localhost/foo?param=value'")); } @Test public void getRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); new HttpieRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo?a=alpha") .param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); } @Test public void getRequestWithDisjointQueryStringAndParameters() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo?a=alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http GET 'http://localhost/foo?a=alpha&b=bravo'")); } @Test public void getRequestWithQueryStringWithNoValue() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http GET 'http://localhost/foo?param'")); new HttpieRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo?param").build()); + assertThat(this.generatedSnippets.httpieRequest()).is( + codeBlock("bash").withContent("$ http GET 'http://localhost/foo?param'")); } @Test public void postRequestWithQueryString() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http POST 'http://localhost/foo?param=value'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo?param=value").method("POST").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http POST 'http://localhost/foo?param=value'")); } @Test public void postRequestWithQueryStringWithNoValue() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http POST 'http://localhost/foo?param'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo?param").method("POST").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http POST 'http://localhost/foo?param'")); } @Test public void postRequestWithOneParameter() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http --form POST 'http://localhost/foo' 'k1=v1'")); new HttpieRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo") .method("POST").param("k1", "v1").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http --form POST 'http://localhost/foo' 'k1=v1'")); } @Test public void postRequestWithOneParameterWithNoValue() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http --form POST 'http://localhost/foo' 'k1='")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("POST").param("k1").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http --form POST 'http://localhost/foo' 'k1='")); } @Test public void postRequestWithMultipleParameters() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http --form POST 'http://localhost/foo'" - + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); new HttpieRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo").method("POST") .param("k1", "v1", "v1-bis").param("k2", "v2").build()); + assertThat(this.generatedSnippets.httpieRequest()).is( + codeBlock("bash").withContent("$ http --form POST 'http://localhost/foo'" + + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); } @Test public void postRequestWithUrlEncodedParameter() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http --form POST 'http://localhost/foo' 'k1=a&b'")); new HttpieRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo") .method("POST").param("k1", "a&b").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http --form POST 'http://localhost/foo' 'k1=a&b'")); } @Test public void postRequestWithDisjointQueryStringAndParameter() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); new HttpieRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo?a=alpha") .method("POST").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent( + "$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); } @Test public void postRequestWithTotallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http POST 'http://localhost/foo?a=alpha&b=bravo'")); new HttpieRequestSnippet(this.commandFormatter).document( this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") .method("POST").param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http POST 'http://localhost/foo?a=alpha&b=bravo'")); } @Test public void postRequestWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); new HttpieRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo?a=alpha") .method("POST").param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent( + "$ http --form POST 'http://localhost/foo?a=alpha' 'b=bravo'")); } @Test public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { - this.snippets.expectHttpieRequest() - .withContents(codeBlock("bash").content( - "$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' " - + "'Content-Type:application/x-www-form-urlencoded'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("POST").content("a=alpha&b=bravo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent( + "$ echo 'a=alpha&b=bravo' | http POST 'http://localhost/foo' " + + "'Content-Type:application/x-www-form-urlencoded'")); } @Test public void putRequestWithOneParameter() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http --form PUT 'http://localhost/foo' 'k1=v1'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("PUT").param("k1", "v1").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http --form PUT 'http://localhost/foo' 'k1=v1'")); } @Test public void putRequestWithMultipleParameters() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http --form PUT 'http://localhost/foo'" - + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("PUT").param("k1", "v1") .param("k1", "v1-bis").param("k2", "v2").build()); + assertThat(this.generatedSnippets.httpieRequest()).is( + codeBlock("bash").withContent("$ http --form PUT 'http://localhost/foo'" + + " 'k1=v1' 'k1=v1-bis' 'k2=v2'")); } @Test public void putRequestWithUrlEncodedParameter() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http --form PUT 'http://localhost/foo' 'k1=a&b'")); new HttpieRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo") .method("PUT").param("k1", "a&b").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http --form PUT 'http://localhost/foo' 'k1=a&b'")); } @Test public void requestWithHeaders() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http GET 'http://localhost/foo'" - + " 'Content-Type:application/json' 'a:alpha'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'" + + " 'Content-Type:application/json' 'a:alpha'")); } @Test public void requestWithHeadersMultiline() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content(String.format("$ http GET 'http://localhost/foo' \\%n" - + " 'Content-Type:application/json' \\%n 'a:alpha'"))); new HttpieRequestSnippet(CliDocumentation.multiLineFormat()) .document(this.operationBuilder.request("http://localhost/foo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent(String.format("$ http GET 'http://localhost/foo' \\%n" + + " 'Content-Type:application/json' \\%n 'a:alpha'"))); } @Test public void requestWithCookies() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ http GET 'http://localhost/foo'" - + " 'Cookie:name1=value1' 'Cookie:name2=value2'")); new HttpieRequestSnippet(this.commandFormatter) .document(this.operationBuilder.request("http://localhost/foo") .cookie("name1", "value1").cookie("name2", "value2").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent("$ http GET 'http://localhost/foo'" + + " 'Cookie:name1=value1' 'Cookie:name2=value2'")); } @Test public void multipartPostWithNoSubmittedFileName() throws IOException { - String expectedContent = "$ http --form POST 'http://localhost/upload'" - + " 'metadata'@<(echo '{\"description\": \"foo\"}')"; - this.snippets.expectHttpieRequest() - .withContents(codeBlock("bash").content(expectedContent)); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("metadata", "{\"description\": \"foo\"}".getBytes()).build()); + String expectedContent = "$ http --form POST 'http://localhost/upload'" + + " 'metadata'@<(echo '{\"description\": \"foo\"}')"; + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent(expectedContent)); } @Test public void multipartPostWithContentType() throws IOException { - // httpie does not yet support manually set content type by part - String expectedContent = "$ http --form POST 'http://localhost/upload'" - + " 'image'@'documents/images/example.png'"; - this.snippets.expectHttpieRequest() - .withContents(codeBlock("bash").content(expectedContent)); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", new byte[0]) .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE) .submittedFileName("documents/images/example.png").build()); + // httpie does not yet support manually set content type by part + String expectedContent = "$ http --form POST 'http://localhost/upload'" + + " 'image'@'documents/images/example.png'"; + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent(expectedContent)); } @Test public void multipartPost() throws IOException { - String expectedContent = "$ http --form POST 'http://localhost/upload'" - + " 'image'@'documents/images/example.png'"; - this.snippets.expectHttpieRequest() - .withContents(codeBlock("bash").content(expectedContent)); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", new byte[0]) .submittedFileName("documents/images/example.png").build()); + String expectedContent = "$ http --form POST 'http://localhost/upload'" + + " 'image'@'documents/images/example.png'"; + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent(expectedContent)); } @Test public void multipartPostWithParameters() throws IOException { - String expectedContent = "$ http --form POST 'http://localhost/upload'" - + " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'" - + " 'b=banana'"; - this.snippets.expectHttpieRequest() - .withContents(codeBlock("bash").content(expectedContent)); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", new byte[0]) .submittedFileName("documents/images/example.png").and() .param("a", "apple", "avocado").param("b", "banana").build()); + String expectedContent = "$ http --form POST 'http://localhost/upload'" + + " 'image'@'documents/images/example.png' 'a=apple' 'a=avocado'" + + " 'b=banana'"; + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent(expectedContent)); } @Test public void basicAuthCredentialsAreSuppliedUsingAuthOption() throws IOException { - this.snippets.expectHttpieRequest().withContents(codeBlock("bash") - .content("$ http --auth 'user:secret' GET 'http://localhost/foo'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo") .header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString("user:secret".getBytes())) .build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http --auth 'user:secret' GET 'http://localhost/foo'")); } @Test public void customAttributes() throws IOException { - this.snippets.expectHttpieRequest() - .withContents(containsString("httpie request title")); - TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); - given(resolver.resolveTemplateResource("httpie-request")) - .willReturn(snippetResource("httpie-request-with-title")); - new HttpieRequestSnippet( - attributes(key("title") - .value("httpie request title")), - this.commandFormatter) - .document(this.operationBuilder - .attribute(TemplateEngine.class.getName(), - new MustacheTemplateEngine(resolver)) - .request("http://localhost/foo").build()); - } - - @Test - public void customHostHeaderIsIncluded() throws IOException { - this.snippets.expectHttpieRequest() - .withContents(codeBlock("bash").content( - "$ http GET 'http://localhost/foo' 'Host:api.example.com'" - + " 'Content-Type:application/json' 'a:alpha'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo") .header(HttpHeaders.HOST, "api.example.com") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha").build()); + assertThat(this.generatedSnippets.httpieRequest()).is(codeBlock("bash") + .withContent("$ http GET 'http://localhost/foo' 'Host:api.example.com'" + + " 'Content-Type:application/json' 'a:alpha'")); } @Test public void postWithContentAndParameters() throws IOException { - this.snippets.expectHttpieRequest().withContents( - codeBlock("bash").content("$ echo 'Some content' | http POST " - + "'http://localhost/foo?a=alpha&b=bravo'")); new HttpieRequestSnippet(this.commandFormatter).document(this.operationBuilder .request("http://localhost/foo").method("POST").param("a", "alpha") .param("b", "bravo").content("Some content").build()); + assertThat(this.generatedSnippets.httpieRequest()) + .is(codeBlock("bash").withContent("$ echo 'Some content' | http POST " + + "'http://localhost/foo?a=alpha&b=bravo'")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java index c4d16936..b0f554d2 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/config/RestDocumentationConfigurerTests.java @@ -22,7 +22,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.http.HttpHeaders; @@ -54,13 +53,7 @@ import org.springframework.restdocs.templates.mustache.AsciidoctorTableCellConte import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; import org.springframework.test.util.ReflectionTestUtils; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; /** @@ -78,37 +71,38 @@ public class RestDocumentationConfigurerTests { public void defaultConfiguration() { Map configuration = new HashMap<>(); this.configurer.apply(configuration, createContext()); - assertThat(configuration, hasEntry(equalTo(TemplateEngine.class.getName()), - instanceOf(MustacheTemplateEngine.class))); - assertThat(configuration, hasEntry(equalTo(WriterResolver.class.getName()), - instanceOf(StandardWriterResolver.class))); - assertThat(configuration, - hasEntry(equalTo( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS), - instanceOf(List.class))); + assertThat(configuration).containsKey(TemplateEngine.class.getName()); + assertThat(configuration.get(TemplateEngine.class.getName())) + .isInstanceOf(MustacheTemplateEngine.class); + assertThat(configuration).containsKey(WriterResolver.class.getName()); + assertThat(configuration.get(WriterResolver.class.getName())) + .isInstanceOf(StandardWriterResolver.class); + assertThat(configuration) + .containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + assertThat(configuration + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS)) + .isInstanceOf(List.class); List defaultSnippets = (List) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - assertThat(defaultSnippets, - contains(instanceOf(CurlRequestSnippet.class), - instanceOf(HttpieRequestSnippet.class), - instanceOf(HttpRequestSnippet.class), - instanceOf(HttpResponseSnippet.class), - instanceOf(RequestBodySnippet.class), - instanceOf(ResponseBodySnippet.class))); - assertThat(configuration, hasEntry(equalTo(SnippetConfiguration.class.getName()), - instanceOf(SnippetConfiguration.class))); + assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder( + CurlRequestSnippet.class, HttpieRequestSnippet.class, + HttpRequestSnippet.class, HttpResponseSnippet.class, + RequestBodySnippet.class, ResponseBodySnippet.class); + assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); + assertThat(configuration.get(SnippetConfiguration.class.getName())) + .isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); - assertThat(snippetConfiguration.getEncoding(), is(equalTo("UTF-8"))); - assertThat(snippetConfiguration.getTemplateFormat().getId(), - is(equalTo(TemplateFormats.asciidoctor().getId()))); + assertThat(snippetConfiguration.getEncoding()).isEqualTo("UTF-8"); + assertThat(snippetConfiguration.getTemplateFormat().getId()) + .isEqualTo(TemplateFormats.asciidoctor().getId()); OperationRequestPreprocessor defaultOperationRequestPreprocessor = (OperationRequestPreprocessor) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR); - assertThat(defaultOperationRequestPreprocessor, is(nullValue())); + assertThat(defaultOperationRequestPreprocessor).isNull(); OperationResponsePreprocessor defaultOperationResponsePreprocessor = (OperationResponsePreprocessor) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR); - assertThat(defaultOperationResponsePreprocessor, is(nullValue())); + assertThat(defaultOperationResponsePreprocessor).isNull(); } @Test @@ -117,8 +111,8 @@ public class RestDocumentationConfigurerTests { TemplateEngine templateEngine = mock(TemplateEngine.class); this.configurer.templateEngine(templateEngine).apply(configuration, createContext()); - assertThat(configuration, Matchers.hasEntry( - TemplateEngine.class.getName(), templateEngine)); + assertThat(configuration).containsEntry(TemplateEngine.class.getName(), + templateEngine); } @Test @@ -127,8 +121,8 @@ public class RestDocumentationConfigurerTests { WriterResolver writerResolver = mock(WriterResolver.class); this.configurer.writerResolver(writerResolver).apply(configuration, createContext()); - assertThat(configuration, Matchers.hasEntry( - WriterResolver.class.getName(), writerResolver)); + assertThat(configuration).containsEntry(WriterResolver.class.getName(), + writerResolver); } @Test @@ -136,14 +130,16 @@ public class RestDocumentationConfigurerTests { Map configuration = new HashMap<>(); this.configurer.snippets().withDefaults(CliDocumentation.curlRequest()) .apply(configuration, createContext()); - assertThat(configuration, - hasEntry(equalTo( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS), - instanceOf(List.class))); + assertThat(configuration) + .containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + assertThat(configuration + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS)) + .isInstanceOf(List.class); @SuppressWarnings("unchecked") List defaultSnippets = (List) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - assertThat(defaultSnippets, contains(instanceOf(CurlRequestSnippet.class))); + assertThat(defaultSnippets).hasSize(1); + assertThat(defaultSnippets).hasOnlyElementsOfType(CurlRequestSnippet.class); } @SuppressWarnings("unchecked") @@ -153,19 +149,17 @@ public class RestDocumentationConfigurerTests { Snippet snippet = mock(Snippet.class); this.configurer.snippets().withAdditionalDefaults(snippet).apply(configuration, createContext()); - assertThat(configuration, - hasEntry(equalTo( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS), - instanceOf(List.class))); + assertThat(configuration) + .containsKey(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); + assertThat(configuration + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS)) + .isInstanceOf(List.class); List defaultSnippets = (List) configuration .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS); - assertThat(defaultSnippets, - contains(instanceOf(CurlRequestSnippet.class), - instanceOf(HttpieRequestSnippet.class), - instanceOf(HttpRequestSnippet.class), - instanceOf(HttpResponseSnippet.class), - instanceOf(RequestBodySnippet.class), - instanceOf(ResponseBodySnippet.class), equalTo(snippet))); + assertThat(defaultSnippets).extracting("class").containsExactlyInAnyOrder( + CurlRequestSnippet.class, HttpieRequestSnippet.class, + HttpRequestSnippet.class, HttpResponseSnippet.class, + RequestBodySnippet.class, ResponseBodySnippet.class, snippet.getClass()); } @Test @@ -173,11 +167,12 @@ public class RestDocumentationConfigurerTests { Map configuration = new HashMap<>(); this.configurer.snippets().withEncoding("ISO 8859-1").apply(configuration, createContext()); - assertThat(configuration, hasEntry(equalTo(SnippetConfiguration.class.getName()), - instanceOf(SnippetConfiguration.class))); + assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); + assertThat(configuration.get(SnippetConfiguration.class.getName())) + .isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); - assertThat(snippetConfiguration.getEncoding(), is(equalTo("ISO 8859-1"))); + assertThat(snippetConfiguration.getEncoding()).isEqualTo("ISO 8859-1"); } @Test @@ -185,12 +180,13 @@ public class RestDocumentationConfigurerTests { Map configuration = new HashMap<>(); this.configurer.snippets().withTemplateFormat(TemplateFormats.markdown()) .apply(configuration, createContext()); - assertThat(configuration, hasEntry(equalTo(SnippetConfiguration.class.getName()), - instanceOf(SnippetConfiguration.class))); + assertThat(configuration).containsKey(SnippetConfiguration.class.getName()); + assertThat(configuration.get(SnippetConfiguration.class.getName())) + .isInstanceOf(SnippetConfiguration.class); SnippetConfiguration snippetConfiguration = (SnippetConfiguration) configuration .get(SnippetConfiguration.class.getName()); - assertThat(snippetConfiguration.getTemplateFormat().getId(), - is(equalTo(TemplateFormats.markdown().getId()))); + assertThat(snippetConfiguration.getTemplateFormat().getId()) + .isEqualTo(TemplateFormats.markdown().getId()); } @SuppressWarnings("unchecked") @@ -203,8 +199,9 @@ public class RestDocumentationConfigurerTests { MustacheTemplateEngine mustacheTemplateEngine = (MustacheTemplateEngine) templateEngine; Map templateContext = (Map) ReflectionTestUtils .getField(mustacheTemplateEngine, "context"); - assertThat(templateContext, hasEntry(equalTo("tableCellContent"), - instanceOf(AsciidoctorTableCellContentLambda.class))); + assertThat(templateContext).containsKey("tableCellContent"); + assertThat(templateContext.get("tableCellContent")) + .isInstanceOf(AsciidoctorTableCellContentLambda.class); } @SuppressWarnings("unchecked") @@ -218,7 +215,7 @@ public class RestDocumentationConfigurerTests { MustacheTemplateEngine mustacheTemplateEngine = (MustacheTemplateEngine) templateEngine; Map templateContext = (Map) ReflectionTestUtils .getField(mustacheTemplateEngine, "context"); - assertThat(templateContext.size(), equalTo(0)); + assertThat(templateContext.size()).isEqualTo(0); } @Test @@ -235,8 +232,8 @@ public class RestDocumentationConfigurerTests { OperationRequest request = new OperationRequestFactory().create( URI.create("http://localhost:8080"), HttpMethod.GET, null, headers, null, Collections.emptyList()); - assertThat(preprocessor.preprocess(request).getHeaders().get("Foo"), - is(nullValue())); + assertThat(preprocessor.preprocess(request).getHeaders()) + .doesNotContainKey("Foo"); } @Test @@ -252,8 +249,8 @@ public class RestDocumentationConfigurerTests { headers.add("Foo", "value"); OperationResponse response = new OperationResponseFactory().create(HttpStatus.OK, headers, null); - assertThat(preprocessor.preprocess(response).getHeaders().get("Foo"), - is(nullValue())); + assertThat(preprocessor.preprocess(response).getHeaders()) + .doesNotContainKey("Foo"); } private RestDocumentationContext createContext() { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java index 70c0d1ab..6d9e057c 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ConstraintDescriptionsTests.java @@ -21,10 +21,7 @@ import java.util.Collections; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -56,16 +53,16 @@ public class ConstraintDescriptionsTests { .willReturn("Bravo"); given(this.constraintDescriptionResolver.resolveDescription(constraint2)) .willReturn("Alpha"); - assertThat(this.constraintDescriptions.descriptionsForProperty("foo"), - contains("Alpha", "Bravo")); + assertThat(this.constraintDescriptions.descriptionsForProperty("foo")) + .containsExactly("Alpha", "Bravo"); } @Test public void emptyListOfDescriptionsWhenThereAreNoConstraints() { given(this.constraintResolver.resolveForProperty("foo", Constrained.class)) .willReturn(Collections.emptyList()); - assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size(), - is(equalTo(0))); + assertThat(this.constraintDescriptions.descriptionsForProperty("foo").size()) + .isEqualTo(0); } private static class Constrained { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java index 95d26e91..8be26ab2 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ResourceBundleConstraintDescriptionResolverTests.java @@ -65,9 +65,7 @@ import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ResourceBundleConstraintDescriptionResolver}. @@ -80,217 +78,214 @@ public class ResourceBundleConstraintDescriptionResolverTests { @Test public void defaultMessageAssertFalse() { - assertThat(constraintDescriptionForField("assertFalse"), - is(equalTo("Must be false"))); + assertThat(constraintDescriptionForField("assertFalse")) + .isEqualTo("Must be false"); } @Test public void defaultMessageAssertTrue() { - assertThat(constraintDescriptionForField("assertTrue"), - is(equalTo("Must be true"))); + assertThat(constraintDescriptionForField("assertTrue")).isEqualTo("Must be true"); } @Test public void defaultMessageCodePointLength() { - assertThat(constraintDescriptionForField("codePointLength"), - is(equalTo("Code point length must be between 2 and 5 inclusive"))); + assertThat(constraintDescriptionForField("codePointLength")) + .isEqualTo("Code point length must be between 2 and 5 inclusive"); } @Test public void defaultMessageCurrency() { - assertThat(constraintDescriptionForField("currency"), - is(equalTo("Must be in an accepted currency unit (GBP, USD)"))); + assertThat(constraintDescriptionForField("currency")) + .isEqualTo("Must be in an accepted currency unit (GBP, USD)"); } @Test public void defaultMessageDecimalMax() { - assertThat(constraintDescriptionForField("decimalMax"), - is(equalTo("Must be at most 9.875"))); + assertThat(constraintDescriptionForField("decimalMax")) + .isEqualTo("Must be at most 9.875"); } @Test public void defaultMessageDecimalMin() { - assertThat(constraintDescriptionForField("decimalMin"), - is(equalTo("Must be at least 1.5"))); + assertThat(constraintDescriptionForField("decimalMin")) + .isEqualTo("Must be at least 1.5"); } @Test public void defaultMessageDigits() { - assertThat(constraintDescriptionForField("digits"), is( - equalTo("Must have at most 2 integral digits and 5 fractional digits"))); + assertThat(constraintDescriptionForField("digits")) + .isEqualTo("Must have at most 2 integral digits and 5 fractional digits"); } @Test public void defaultMessageFuture() { - assertThat(constraintDescriptionForField("future"), - is(equalTo("Must be in the future"))); + assertThat(constraintDescriptionForField("future")) + .isEqualTo("Must be in the future"); } @Test public void defaultMessageFutureOrPresent() { - assertThat(constraintDescriptionForField("futureOrPresent"), - is(equalTo("Must be in the future or the present"))); + assertThat(constraintDescriptionForField("futureOrPresent")) + .isEqualTo("Must be in the future or the present"); } @Test public void defaultMessageMax() { - assertThat(constraintDescriptionForField("max"), - is(equalTo("Must be at most 10"))); + assertThat(constraintDescriptionForField("max")).isEqualTo("Must be at most 10"); } @Test public void defaultMessageMin() { - assertThat(constraintDescriptionForField("min"), - is(equalTo("Must be at least 10"))); + assertThat(constraintDescriptionForField("min")).isEqualTo("Must be at least 10"); } @Test public void defaultMessageNotNull() { - assertThat(constraintDescriptionForField("notNull"), - is(equalTo("Must not be null"))); + assertThat(constraintDescriptionForField("notNull")) + .isEqualTo("Must not be null"); } @Test public void defaultMessageNull() { - assertThat(constraintDescriptionForField("nul"), is(equalTo("Must be null"))); + assertThat(constraintDescriptionForField("nul")).isEqualTo("Must be null"); } @Test public void defaultMessagePast() { - assertThat(constraintDescriptionForField("past"), - is(equalTo("Must be in the past"))); + assertThat(constraintDescriptionForField("past")) + .isEqualTo("Must be in the past"); } @Test public void defaultMessagePastOrPresent() { - assertThat(constraintDescriptionForField("pastOrPresent"), - is(equalTo("Must be in the past or the present"))); + assertThat(constraintDescriptionForField("pastOrPresent")) + .isEqualTo("Must be in the past or the present"); } @Test public void defaultMessagePattern() { - assertThat(constraintDescriptionForField("pattern"), - is(equalTo("Must match the regular expression `[A-Z][a-z]+`"))); + assertThat(constraintDescriptionForField("pattern")) + .isEqualTo("Must match the regular expression `[A-Z][a-z]+`"); } @Test public void defaultMessageSize() { - assertThat(constraintDescriptionForField("size"), - is(equalTo("Size must be between 2 and 10 inclusive"))); + assertThat(constraintDescriptionForField("size")) + .isEqualTo("Size must be between 2 and 10 inclusive"); } @Test public void defaultMessageCreditCardNumber() { - assertThat(constraintDescriptionForField("creditCardNumber"), - is(equalTo("Must be a well-formed credit card number"))); + assertThat(constraintDescriptionForField("creditCardNumber")) + .isEqualTo("Must be a well-formed credit card number"); } @Test public void defaultMessageEan() { - assertThat(constraintDescriptionForField("ean"), - is(equalTo("Must be a well-formed EAN13 number"))); + assertThat(constraintDescriptionForField("ean")) + .isEqualTo("Must be a well-formed EAN13 number"); } @Test public void defaultMessageEmail() { - assertThat(constraintDescriptionForField("email"), - is(equalTo("Must be a well-formed email address"))); + assertThat(constraintDescriptionForField("email")) + .isEqualTo("Must be a well-formed email address"); } @Test public void defaultMessageEmailHibernateValidator() { - assertThat(constraintDescriptionForField("emailHibernateValidator"), - is(equalTo("Must be a well-formed email address"))); + assertThat(constraintDescriptionForField("emailHibernateValidator")) + .isEqualTo("Must be a well-formed email address"); } @Test public void defaultMessageLength() { - assertThat(constraintDescriptionForField("length"), - is(equalTo("Length must be between 2 and 10 inclusive"))); + assertThat(constraintDescriptionForField("length")) + .isEqualTo("Length must be between 2 and 10 inclusive"); } @Test public void defaultMessageLuhnCheck() { - assertThat(constraintDescriptionForField("luhnCheck"), - is(equalTo("Must pass the Luhn Modulo 10 checksum algorithm"))); + assertThat(constraintDescriptionForField("luhnCheck")) + .isEqualTo("Must pass the Luhn Modulo 10 checksum algorithm"); } @Test public void defaultMessageMod10Check() { - assertThat(constraintDescriptionForField("mod10Check"), - is(equalTo("Must pass the Mod10 checksum algorithm"))); + assertThat(constraintDescriptionForField("mod10Check")) + .isEqualTo("Must pass the Mod10 checksum algorithm"); } @Test public void defaultMessageMod11Check() { - assertThat(constraintDescriptionForField("mod11Check"), - is(equalTo("Must pass the Mod11 checksum algorithm"))); + assertThat(constraintDescriptionForField("mod11Check")) + .isEqualTo("Must pass the Mod11 checksum algorithm"); } @Test public void defaultMessageNegative() { - assertThat(constraintDescriptionForField("negative"), - is(equalTo("Must be negative"))); + assertThat(constraintDescriptionForField("negative")) + .isEqualTo("Must be negative"); } @Test public void defaultMessageNegativeOrZero() { - assertThat(constraintDescriptionForField("negativeOrZero"), - is(equalTo("Must be negative or zero"))); + assertThat(constraintDescriptionForField("negativeOrZero")) + .isEqualTo("Must be negative or zero"); } @Test public void defaultMessageNotBlank() { - assertThat(constraintDescriptionForField("notBlank"), - is(equalTo("Must not be blank"))); + assertThat(constraintDescriptionForField("notBlank")) + .isEqualTo("Must not be blank"); } @Test public void defaultMessageNotBlankHibernateValidator() { - assertThat(constraintDescriptionForField("notBlankHibernateValidator"), - is(equalTo("Must not be blank"))); + assertThat(constraintDescriptionForField("notBlankHibernateValidator")) + .isEqualTo("Must not be blank"); } @Test public void defaultMessageNotEmpty() { - assertThat(constraintDescriptionForField("notEmpty"), - is(equalTo("Must not be empty"))); + assertThat(constraintDescriptionForField("notEmpty")) + .isEqualTo("Must not be empty"); } @Test public void defaultMessageNotEmptyHibernateValidator() { - assertThat(constraintDescriptionForField("notEmpty"), - is(equalTo("Must not be empty"))); + assertThat(constraintDescriptionForField("notEmpty")) + .isEqualTo("Must not be empty"); } @Test public void defaultMessagePositive() { - assertThat(constraintDescriptionForField("positive"), - is(equalTo("Must be positive"))); + assertThat(constraintDescriptionForField("positive")) + .isEqualTo("Must be positive"); } @Test public void defaultMessagePositiveOrZero() { - assertThat(constraintDescriptionForField("positiveOrZero"), - is(equalTo("Must be positive or zero"))); + assertThat(constraintDescriptionForField("positiveOrZero")) + .isEqualTo("Must be positive or zero"); } @Test public void defaultMessageRange() { - assertThat(constraintDescriptionForField("range"), - is(equalTo("Must be at least 10 and at most 100"))); + assertThat(constraintDescriptionForField("range")) + .isEqualTo("Must be at least 10 and at most 100"); } @Test public void defaultMessageSafeHtml() { - assertThat(constraintDescriptionForField("safeHtml"), - is(equalTo("Must be safe HTML"))); + assertThat(constraintDescriptionForField("safeHtml")) + .isEqualTo("Must be safe HTML"); } @Test public void defaultMessageUrl() { - assertThat(constraintDescriptionForField("url"), - is(equalTo("Must be a well-formed URL"))); + assertThat(constraintDescriptionForField("url")) + .isEqualTo("Must be a well-formed URL"); } @Test @@ -313,7 +308,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { String description = new ResourceBundleConstraintDescriptionResolver() .resolveDescription(new Constraint(NotNull.class.getName(), Collections.emptyMap())); - assertThat(description, is(equalTo("Should not be null"))); + assertThat(description).isEqualTo("Should not be null"); } finally { @@ -335,7 +330,7 @@ public class ResourceBundleConstraintDescriptionResolverTests { String description = new ResourceBundleConstraintDescriptionResolver(bundle) .resolveDescription(new Constraint(NotNull.class.getName(), Collections.emptyMap())); - assertThat(description, is(equalTo("Not null"))); + assertThat(description).isEqualTo("Not null"); } private String constraintDescriptionForField(String name) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java index 96b176b0..8734a3c1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/constraints/ValidatorConstraintResolverTests.java @@ -32,16 +32,13 @@ import javax.validation.constraints.NotNull; import javax.validation.constraints.Null; import javax.validation.constraints.Size; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; +import org.assertj.core.api.Condition; +import org.assertj.core.description.TextDescription; import org.hibernate.validator.constraints.CompositionType; import org.hibernate.validator.constraints.ConstraintComposition; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ValidatorConstraintResolver}. @@ -56,36 +53,36 @@ public class ValidatorConstraintResolverTests { public void singleFieldConstraint() { List constraints = this.resolver.resolveForProperty("single", ConstrainedFields.class); - assertThat(constraints, hasSize(1)); - assertThat(constraints.get(0).getName(), is(NotNull.class.getName())); + assertThat(constraints).hasSize(1); + assertThat(constraints.get(0).getName()).isEqualTo(NotNull.class.getName()); } - @SuppressWarnings("unchecked") @Test public void multipleFieldConstraints() { List constraints = this.resolver.resolveForProperty("multiple", ConstrainedFields.class); - assertThat(constraints, hasSize(2)); - assertThat(constraints, containsInAnyOrder(constraint(NotNull.class), - constraint(Size.class).config("min", 8).config("max", 16))); + assertThat(constraints).hasSize(2); + assertThat(constraints.get(0)).is(constraint(NotNull.class)); + assertThat(constraints.get(1)) + .is(constraint(Size.class).config("min", 8).config("max", 16)); } @Test public void noFieldConstraints() { List constraints = this.resolver.resolveForProperty("none", ConstrainedFields.class); - assertThat(constraints, hasSize(0)); + assertThat(constraints).hasSize(0); } @Test public void compositeConstraint() { List constraints = this.resolver.resolveForProperty("composite", ConstrainedFields.class); - assertThat(constraints, hasSize(1)); + assertThat(constraints).hasSize(1); } - private ConstraintMatcher constraint(final Class annotation) { - return new ConstraintMatcher(annotation); + private ConstraintCondition constraint(final Class annotation) { + return new ConstraintCondition(annotation); } private static class ConstrainedFields { @@ -121,27 +118,25 @@ public class ValidatorConstraintResolverTests { } - private static final class ConstraintMatcher extends BaseMatcher { + private static final class ConstraintCondition extends Condition { private final Class annotation; private final Map configuration = new HashMap<>(); - private ConstraintMatcher(Class annotation) { + private ConstraintCondition(Class annotation) { this.annotation = annotation; + as(new TextDescription("Constraint named %s with configuration %s", + this.annotation, this.configuration)); } - public ConstraintMatcher config(String key, Object value) { + public ConstraintCondition config(String key, Object value) { this.configuration.put(key, value); return this; } @Override - public boolean matches(Object item) { - if (!(item instanceof Constraint)) { - return false; - } - Constraint constraint = (Constraint) item; + public boolean matches(Constraint constraint) { if (!constraint.getName().equals(this.annotation.getName())) { return false; } @@ -154,12 +149,6 @@ public class ValidatorConstraintResolverTests { return true; } - @Override - public void describeTo(Description description) { - description.appendText("Constraint named " + this.annotation.getName() - + " with configuration " + this.configuration); - } - } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java index e2eba481..95f27678 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetFailureTests.java @@ -24,7 +24,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.test.ExpectedSnippets; import org.springframework.restdocs.test.OperationBuilder; import static org.hamcrest.CoreMatchers.endsWith; @@ -43,9 +42,6 @@ public class RequestHeadersSnippetFailureTests { @Rule public OperationBuilder operationBuilder = new OperationBuilder(asciidoctor()); - @Rule - public ExpectedSnippets snippets = new ExpectedSnippets(asciidoctor()); - @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java index 81318305..26820edd 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/RequestHeadersSnippetTests.java @@ -28,7 +28,7 @@ import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; @@ -49,12 +49,6 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { @Test public void requestWithHeaders() throws IOException { - this.snippets.expectRequestHeaders() - .withContents(tableWithHeader("Name", "Description") - .row("`X-Test`", "one").row("`Accept`", "two") - .row("`Accept-Encoding`", "three") - .row("`Accept-Language`", "four").row("`Cache-Control`", "five") - .row("`Connection`", "six")); new RequestHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one"), headerWithName("Accept").description("two"), @@ -68,32 +62,36 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { .header("Accept-Language", "en-US,en;q=0.5") .header("Cache-Control", "max-age=0") .header("Connection", "keep-alive").build()); + assertThat(this.generatedSnippets.requestHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") + .row("`Accept`", "two").row("`Accept-Encoding`", "three") + .row("`Accept-Language`", "four").row("`Cache-Control`", "five") + .row("`Connection`", "six")); } @Test public void caseInsensitiveRequestHeaders() throws IOException { - this.snippets.expectRequestHeaders().withContents( - tableWithHeader("Name", "Description").row("`X-Test`", "one")); new RequestHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one"))) .document(this.operationBuilder.request("/") .header("X-test", "test").build()); + assertThat(this.generatedSnippets.requestHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); } @Test public void undocumentedRequestHeader() throws IOException { - this.snippets.expectRequestHeaders().withContents( - tableWithHeader("Name", "Description").row("`X-Test`", "one")); new RequestHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one"))) .document(this.operationBuilder.request("http://localhost") .header("X-Test", "test").header("Accept", "*/*") .build()); + assertThat(this.generatedSnippets.requestHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); } @Test public void requestHeadersWithCustomAttributes() throws IOException { - this.snippets.expectRequestHeaders().withContents(containsString("Custom title")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-headers")) .willReturn(snippetResource("request-headers-with-title")); @@ -107,15 +105,11 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { resolver)) .request("http://localhost") .header("X-Test", "test").build()); + assertThat(this.generatedSnippets.requestHeaders()).contains("Custom title"); } @Test public void requestHeadersWithCustomDescriptorAttributes() throws IOException { - this.snippets.expectRequestHeaders().withContents(// - tableWithHeader("Name", "Description", "Foo") - .row("X-Test", "one", "alpha") - .row("Accept-Encoding", "two", "bravo") - .row("Accept", "three", "charlie")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-headers")) .willReturn(snippetResource("request-headers-with-extra-column")); @@ -136,16 +130,15 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { .header("Accept-Encoding", "gzip, deflate") .header("Accept", "*/*").build()); + assertThat(this.generatedSnippets.requestHeaders()).is(// + tableWithHeader("Name", "Description", "Foo") + .row("X-Test", "one", "alpha") + .row("Accept-Encoding", "two", "bravo") + .row("Accept", "three", "charlie")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectRequestHeaders() - .withContents(tableWithHeader("Name", "Description") - .row("`X-Test`", "one").row("`Accept`", "two") - .row("`Accept-Encoding`", "three") - .row("`Accept-Language`", "four").row("`Cache-Control`", "five") - .row("`Connection`", "six")); HeaderDocumentation .requestHeaders(headerWithName("X-Test").description("one"), headerWithName("Accept").description("two"), @@ -159,17 +152,22 @@ public class RequestHeadersSnippetTests extends AbstractSnippetTests { .header("Accept-Language", "en-US,en;q=0.5") .header("Cache-Control", "max-age=0") .header("Connection", "keep-alive").build()); + assertThat(this.generatedSnippets.requestHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") + .row("`Accept`", "two").row("`Accept-Encoding`", "three") + .row("`Accept-Language`", "four").row("`Cache-Control`", "five") + .row("`Connection`", "six")); } @Test public void tableCellContentIsEscapedWhenNecessary() throws IOException { - this.snippets.expectRequestHeaders().withContents( - tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"), - escapeIfNecessary("one|two"))); new RequestHeadersSnippet( Arrays.asList(headerWithName("Foo|Bar").description("one|two"))) .document(this.operationBuilder.request("http://localhost") .header("Foo|Bar", "baz").build()); + assertThat(this.generatedSnippets.requestHeaders()).is( + tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"), + escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java index 72d38fcc..6df4929b 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetFailureTests.java @@ -24,7 +24,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.test.ExpectedSnippets; import org.springframework.restdocs.test.OperationBuilder; import static org.hamcrest.CoreMatchers.endsWith; @@ -43,9 +42,6 @@ public class ResponseHeadersSnippetFailureTests { @Rule public OperationBuilder operationBuilder = new OperationBuilder(asciidoctor()); - @Rule - public ExpectedSnippets snippets = new ExpectedSnippets(asciidoctor()); - @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java index 0156812f..4fbd51f0 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/headers/ResponseHeadersSnippetTests.java @@ -28,7 +28,7 @@ import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; @@ -49,10 +49,6 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { @Test public void responseWithHeaders() throws IOException { - this.snippets.expectResponseHeaders().withContents( - tableWithHeader("Name", "Description").row("`X-Test`", "one") - .row("`Content-Type`", "two").row("`Etag`", "three") - .row("`Cache-Control`", "five").row("`Vary`", "six")); new ResponseHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one"), headerWithName("Content-Type").description("two"), @@ -64,32 +60,34 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { .header("Etag", "lskjadldj3ii32l2ij23") .header("Cache-Control", "max-age=0") .header("Vary", "User-Agent").build()); + assertThat(this.generatedSnippets.responseHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") + .row("`Content-Type`", "two").row("`Etag`", "three") + .row("`Cache-Control`", "five").row("`Vary`", "six")); } @Test public void caseInsensitiveResponseHeaders() throws IOException { - this.snippets.expectResponseHeaders().withContents( - tableWithHeader("Name", "Description").row("`X-Test`", "one")); new ResponseHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one"))) .document(this.operationBuilder.response() .header("X-test", "test").build()); + assertThat(this.generatedSnippets.responseHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); } @Test public void undocumentedResponseHeader() throws IOException { - this.snippets.expectResponseHeaders().withContents( - tableWithHeader("Name", "Description").row("`X-Test`", "one")); new ResponseHeadersSnippet( Arrays.asList(headerWithName("X-Test").description("one"))).document( this.operationBuilder.response().header("X-Test", "test") .header("Content-Type", "*/*").build()); + assertThat(this.generatedSnippets.responseHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one")); } @Test public void responseHeadersWithCustomAttributes() throws IOException { - this.snippets.expectResponseHeaders() - .withContents(containsString("Custom title")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-headers")) .willReturn(snippetResource("response-headers-with-title")); @@ -103,14 +101,11 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { resolver)) .response().header("X-Test", "test") .build()); + assertThat(this.generatedSnippets.responseHeaders()).contains("Custom title"); } @Test public void responseHeadersWithCustomDescriptorAttributes() throws IOException { - this.snippets.expectResponseHeaders() - .withContents(tableWithHeader("Name", "Description", "Foo") - .row("X-Test", "one", "alpha").row("Content-Type", "two", "bravo") - .row("Etag", "three", "charlie")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-headers")) .willReturn(snippetResource("response-headers-with-extra-column")); @@ -131,14 +126,14 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { "application/json") .header("Etag", "lskjadldj3ii32l2ij23") .build()); + assertThat(this.generatedSnippets.responseHeaders()) + .is(tableWithHeader("Name", "Description", "Foo") + .row("X-Test", "one", "alpha").row("Content-Type", "two", "bravo") + .row("Etag", "three", "charlie")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectResponseHeaders().withContents( - tableWithHeader("Name", "Description").row("`X-Test`", "one") - .row("`Content-Type`", "two").row("`Etag`", "three") - .row("`Cache-Control`", "five").row("`Vary`", "six")); HeaderDocumentation .responseHeaders(headerWithName("X-Test").description("one"), headerWithName("Content-Type").description("two"), @@ -150,17 +145,21 @@ public class ResponseHeadersSnippetTests extends AbstractSnippetTests { .header("Etag", "lskjadldj3ii32l2ij23") .header("Cache-Control", "max-age=0").header("Vary", "User-Agent") .build()); + assertThat(this.generatedSnippets.responseHeaders()) + .is(tableWithHeader("Name", "Description").row("`X-Test`", "one") + .row("`Content-Type`", "two").row("`Etag`", "three") + .row("`Cache-Control`", "five").row("`Vary`", "six")); } @Test public void tableCellContentIsEscapedWhenNecessary() throws IOException { - this.snippets.expectResponseHeaders().withContents( - tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"), - escapeIfNecessary("one|two"))); new ResponseHeadersSnippet( Arrays.asList(headerWithName("Foo|Bar").description("one|two"))) .document(this.operationBuilder.response() .header("Foo|Bar", "baz").build()); + assertThat(this.generatedSnippets.responseHeaders()).is( + tableWithHeader("Name", "Description").row(escapeIfNecessary("`Foo|Bar`"), + escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java index 0de3b5ae..6f289144 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpRequestSnippetTests.java @@ -29,7 +29,7 @@ import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; import org.springframework.web.bind.annotation.RequestMethod; -import static org.hamcrest.CoreMatchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.snippet.Attributes.attributes; @@ -51,274 +51,262 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { @Test public void getRequest() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a") - .header(HttpHeaders.HOST, "localhost")); - new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/foo").header("Alpha", "a").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a") + .header(HttpHeaders.HOST, "localhost")); } @Test public void getRequestWithParameters() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo?b=bravo") - .header("Alpha", "a").header(HttpHeaders.HOST, "localhost")); - new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo") .header("Alpha", "a").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo?b=bravo").header("Alpha", "a") + .header(HttpHeaders.HOST, "localhost")); } @Test public void getRequestWithPort() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a") - .header(HttpHeaders.HOST, "localhost:8080")); - new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost:8080/foo").header("Alpha", "a").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo").header("Alpha", "a") + .header(HttpHeaders.HOST, "localhost:8080")); } @Test public void getRequestWithCookies() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo") - .header(HttpHeaders.HOST, "localhost") - .header(HttpHeaders.COOKIE, "name1=value1") - .header(HttpHeaders.COOKIE, "name2=value2")); - new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo") .cookie("name1", "value1").cookie("name2", "value2").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo") + .header(HttpHeaders.HOST, "localhost") + .header(HttpHeaders.COOKIE, "name1=value1") + .header(HttpHeaders.COOKIE, "name2=value2")); } @Test public void getRequestWithQueryString() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo?bar=baz") - .header(HttpHeaders.HOST, "localhost")); - new HttpRequestSnippet().document( this.operationBuilder.request("http://localhost/foo?bar=baz").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo?bar=baz") + .header(HttpHeaders.HOST, "localhost")); } @Test public void getRequestWithQueryStringWithNoValue() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo?bar") - .header(HttpHeaders.HOST, "localhost")); - new HttpRequestSnippet().document( this.operationBuilder.request("http://localhost/foo?bar").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo?bar").header(HttpHeaders.HOST, + "localhost")); } @Test public void getWithPartiallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo") - .header(HttpHeaders.HOST, "localhost")); - new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo?a=alpha") .param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo") + .header(HttpHeaders.HOST, "localhost")); } @Test public void getWithTotallyOverlappingQueryStringAndParameters() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo") - .header(HttpHeaders.HOST, "localhost")); - new HttpRequestSnippet().document( this.operationBuilder.request("http://localhost/foo?a=alpha&b=bravo") .param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo?a=alpha&b=bravo") + .header(HttpHeaders.HOST, "localhost")); } @Test public void postRequestWithContent() throws IOException { String content = "Hello, world"; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo") - .header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/foo").method("POST").content(content).build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo") + .header(HttpHeaders.HOST, "localhost").content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithContentAndParameters() throws IOException { String content = "Hello, world"; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo?a=alpha") - .header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo") .method("POST").param("a", "alpha").content(content).build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo?a=alpha") + .header(HttpHeaders.HOST, "localhost").content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); + } @Test public void postRequestWithContentAndDisjointQueryStringAndParameters() throws IOException { String content = "Hello, world"; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha") - .header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo?b=bravo") .method("POST").param("a", "alpha").content(content).build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha") + .header(HttpHeaders.HOST, "localhost").content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithContentAndPartiallyOverlappingQueryStringAndParameters() throws IOException { String content = "Hello, world"; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha") - .header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/foo?b=bravo").method("POST") .param("a", "alpha").param("b", "bravo").content(content).build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha") + .header(HttpHeaders.HOST, "localhost").content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithContentAndTotallyOverlappingQueryStringAndParameters() throws IOException { String content = "Hello, world"; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha") - .header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/foo?b=bravo&a=alpha").method("POST") .param("a", "alpha").param("b", "bravo").content(content).build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo?b=bravo&a=alpha") + .header(HttpHeaders.HOST, "localhost").content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithOverlappingParametersAndFormUrlEncodedBody() throws IOException { String content = "a=alpha&b=bravo"; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo") - .header(HttpHeaders.CONTENT_TYPE, - MediaType.APPLICATION_FORM_URLENCODED_VALUE) - .header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/foo").method("POST").content("a=alpha&b=bravo") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param("a", "alpha").param("b", "bravo").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo") + .header(HttpHeaders.CONTENT_TYPE, + MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .header(HttpHeaders.HOST, "localhost").content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void postRequestWithCharset() throws IOException { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; byte[] contentBytes = japaneseContent.getBytes("UTF-8"); - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo") - .header("Content-Type", "text/plain;charset=UTF-8") - .header(HttpHeaders.HOST, "localhost") - .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length) - .content(japaneseContent)); - new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo") .method("POST").header("Content-Type", "text/plain;charset=UTF-8") .content(contentBytes).build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo") + .header("Content-Type", "text/plain;charset=UTF-8") + .header(HttpHeaders.HOST, "localhost") + .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length) + .content(japaneseContent)); } @Test public void postRequestWithParameter() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo") - .header(HttpHeaders.HOST, "localhost") - .header("Content-Type", "application/x-www-form-urlencoded") - .content("b%26r=baz&a=alpha")); - new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo") .method("POST").param("b&r", "baz").param("a", "alpha").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo") + .header(HttpHeaders.HOST, "localhost") + .header("Content-Type", "application/x-www-form-urlencoded") + .content("b%26r=baz&a=alpha")); } @Test public void postRequestWithParameterWithNoValue() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/foo") + new HttpRequestSnippet().document(this.operationBuilder + .request("http://localhost/foo").method("POST").param("bar").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/foo") .header(HttpHeaders.HOST, "localhost") .header("Content-Type", "application/x-www-form-urlencoded") .content("bar=")); - - new HttpRequestSnippet().document(this.operationBuilder - .request("http://localhost/foo").method("POST").param("bar").build()); } @Test public void putRequestWithContent() throws IOException { String content = "Hello, world"; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.PUT, "/foo") - .header(HttpHeaders.HOST, "localhost").content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); - new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/foo").method("PUT").content(content).build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.PUT, "/foo") + .header(HttpHeaders.HOST, "localhost").content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void putRequestWithParameter() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.PUT, "/foo") - .header(HttpHeaders.HOST, "localhost") - .header("Content-Type", "application/x-www-form-urlencoded") - .content("b%26r=baz&a=alpha")); - new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo") .method("PUT").param("b&r", "baz").param("a", "alpha").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.PUT, "/foo") + .header(HttpHeaders.HOST, "localhost") + .header("Content-Type", "application/x-www-form-urlencoded") + .content("b%26r=baz&a=alpha")); } @Test public void multipartPost() throws IOException { - String expectedContent = createPart(String.format( - "Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>")); - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", - "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", "<< data >>".getBytes()).build()); + String expectedContent = createPart(String.format( + "Content-Disposition: " + "form-data; " + "name=image%n%n<< data >>")); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/upload") + .header("Content-Type", + "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost").content(expectedContent)); } @Test public void multipartPostWithFilename() throws IOException { - String expectedContent = createPart(String.format("Content-Disposition: " - + "form-data; " + "name=image; filename=image.png%n%n<< data >>")); - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", - "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", "<< data >>".getBytes()).submittedFileName("image.png") .build()); + String expectedContent = createPart(String.format("Content-Disposition: " + + "form-data; " + "name=image; filename=image.png%n%n<< data >>")); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/upload") + .header("Content-Type", + "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost").content(expectedContent)); } @Test public void multipartPostWithParameters() throws IOException { + new HttpRequestSnippet().document(this.operationBuilder + .request("http://localhost/upload").method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .param("a", "apple", "avocado").param("b", "banana") + .part("image", "<< data >>".getBytes()).build()); String param1Part = createPart( String.format("Content-Disposition: form-data; " + "name=a%n%napple"), false); @@ -331,67 +319,60 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { String filePart = createPart(String .format("Content-Disposition: form-data; " + "name=image%n%n<< data >>")); String expectedContent = param1Part + param2Part + param3Part + filePart; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/upload") + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost").content(expectedContent)); - new HttpRequestSnippet().document(this.operationBuilder - .request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .param("a", "apple", "avocado").param("b", "banana") - .part("image", "<< data >>".getBytes()).build()); } @Test public void multipartPostWithParameterWithNoValue() throws IOException { + new HttpRequestSnippet().document(this.operationBuilder + .request("http://localhost/upload").method("POST") + .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) + .param("a").part("image", "<< data >>".getBytes()).build()); String paramPart = createPart( String.format("Content-Disposition: form-data; " + "name=a%n"), false); String filePart = createPart(String .format("Content-Disposition: form-data; " + "name=image%n%n<< data >>")); String expectedContent = paramPart + filePart; - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/upload") + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/upload") .header("Content-Type", "multipart/form-data; boundary=" + BOUNDARY) .header(HttpHeaders.HOST, "localhost").content(expectedContent)); - new HttpRequestSnippet().document(this.operationBuilder - .request("http://localhost/upload").method("POST") - .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) - .param("a").part("image", "<< data >>".getBytes()).build()); } @Test public void multipartPostWithContentType() throws IOException { - String expectedContent = createPart( - String.format("Content-Disposition: form-data; name=image%nContent-Type: " - + "image/png%n%n<< data >>")); - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.POST, "/upload") - .header("Content-Type", - "multipart/form-data; boundary=" + BOUNDARY) - .header(HttpHeaders.HOST, "localhost").content(expectedContent)); new HttpRequestSnippet().document(this.operationBuilder .request("http://localhost/upload").method("POST") .header(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE) .part("image", "<< data >>".getBytes()) .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE).build()); + String expectedContent = createPart( + String.format("Content-Disposition: form-data; name=image%nContent-Type: " + + "image/png%n%n<< data >>")); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.POST, "/upload") + .header("Content-Type", + "multipart/form-data; boundary=" + BOUNDARY) + .header(HttpHeaders.HOST, "localhost").content(expectedContent)); } @Test public void getRequestWithCustomHost() throws IOException { - this.snippets.expectHttpRequest() - .withContents(httpRequest(RequestMethod.GET, "/foo") - .header(HttpHeaders.HOST, "api.example.com")); new HttpRequestSnippet() .document(this.operationBuilder.request("http://localhost/foo") .header(HttpHeaders.HOST, "api.example.com").build()); + assertThat(this.generatedSnippets.httpRequest()) + .is(httpRequest(RequestMethod.GET, "/foo").header(HttpHeaders.HOST, + "api.example.com")); } @Test public void requestWithCustomSnippetAttributes() throws IOException { - this.snippets.expectHttpRequest() - .withContents(containsString("Title for the request")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("http-request")) .willReturn(snippetResource("http-request-with-title")); @@ -400,6 +381,8 @@ public class HttpRequestSnippetTests extends AbstractSnippetTests { .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) .request("http://localhost/foo").build()); + assertThat(this.generatedSnippets.httpRequest()) + .contains("Title for the request"); } private String createPart(String content) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java index ef2a549b..4f924809 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/http/HttpResponseSnippetTests.java @@ -29,7 +29,7 @@ import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.snippet.Attributes.attributes; @@ -49,61 +49,60 @@ public class HttpResponseSnippetTests extends AbstractSnippetTests { @Test public void basicResponse() throws IOException { - this.snippets.expectHttpResponse().withContents(httpResponse(HttpStatus.OK)); new HttpResponseSnippet().document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK)); } @Test public void nonOkResponse() throws IOException { - this.snippets.expectHttpResponse() - .withContents(httpResponse(HttpStatus.BAD_REQUEST)); new HttpResponseSnippet().document(this.operationBuilder.response() .status(HttpStatus.BAD_REQUEST.value()).build()); + assertThat(this.generatedSnippets.httpResponse()) + .is(httpResponse(HttpStatus.BAD_REQUEST)); } @Test public void responseWithHeaders() throws IOException { - this.snippets.expectHttpResponse().withContents(httpResponse(HttpStatus.OK) - .header("Content-Type", "application/json").header("a", "alpha")); new HttpResponseSnippet().document(this.operationBuilder.response() .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header("a", "alpha").build()); + assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK) + .header("Content-Type", "application/json").header("a", "alpha")); } @Test public void responseWithContent() throws IOException { String content = "content"; - this.snippets.expectHttpResponse() - .withContents(httpResponse(HttpStatus.OK).content(content) - .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); new HttpResponseSnippet() .document(this.operationBuilder.response().content(content).build()); + assertThat(this.generatedSnippets.httpResponse()) + .is(httpResponse(HttpStatus.OK).content(content) + .header(HttpHeaders.CONTENT_LENGTH, content.getBytes().length)); } @Test public void responseWithCharset() throws IOException { String japaneseContent = "\u30b3\u30f3\u30c6\u30f3\u30c4"; byte[] contentBytes = japaneseContent.getBytes("UTF-8"); - this.snippets.expectHttpResponse() - .withContents(httpResponse(HttpStatus.OK) - .header("Content-Type", "text/plain;charset=UTF-8") - .content(japaneseContent) - .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)); new HttpResponseSnippet().document(this.operationBuilder.response() .header("Content-Type", "text/plain;charset=UTF-8").content(contentBytes) .build()); + assertThat(this.generatedSnippets.httpResponse()).is(httpResponse(HttpStatus.OK) + .header("Content-Type", "text/plain;charset=UTF-8") + .content(japaneseContent) + .header(HttpHeaders.CONTENT_LENGTH, contentBytes.length)); } @Test public void responseWithCustomSnippetAttributes() throws IOException { - this.snippets.expectHttpResponse() - .withContents(containsString("Title for the response")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("http-response")) .willReturn(snippetResource("http-response-with-title")); new HttpResponseSnippet(attributes(key("title").value("Title for the response"))) .document(this.operationBuilder.attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)).build()); + assertThat(this.generatedSnippets.httpResponse()) + .contains("Title for the response"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java index c6fe7802..7898c71f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinkExtractorsPayloadTests.java @@ -36,7 +36,7 @@ import org.springframework.util.FileCopyUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * Parameterized tests for {@link HalLinkExtractor} and {@link AtomLinkExtractor} with @@ -109,7 +109,7 @@ public class LinkExtractorsPayloadTests { for (Link expectedLink : expectedLinks) { expectedLinksByRel.add(expectedLink.getRel(), expectedLink); } - assertEquals(expectedLinksByRel, actualLinks); + assertThat(actualLinks).isEqualTo(expectedLinksByRel); } private OperationResponse createResponse(String contentName) throws IOException { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java index f8d9c6a0..c6b62020 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.test.ExpectedSnippets; import org.springframework.restdocs.test.OperationBuilder; import static org.hamcrest.CoreMatchers.equalTo; @@ -42,9 +41,6 @@ public class LinksSnippetFailureTests { @Rule public OperationBuilder operationBuilder = new OperationBuilder(asciidoctor()); - @Rule - public ExpectedSnippets snippets = new ExpectedSnippets(asciidoctor()); - @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java index 71bf83c0..5fdff546 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/hypermedia/LinksSnippetTests.java @@ -28,7 +28,7 @@ import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.snippet.Attributes.attributes; @@ -47,68 +47,68 @@ public class LinksSnippetTests extends AbstractSnippetTests { @Test public void ignoredLink() throws IOException { - this.snippets.expectLinks().withContents( - tableWithHeader("Relation", "Description").row("`b`", "Link b")); new LinksSnippet( new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").ignored(), new LinkDescriptor("b").description("Link b"))) .document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); } @Test public void allUndocumentedLinksCanBeIgnored() throws IOException { - this.snippets.expectLinks().withContents( - tableWithHeader("Relation", "Description").row("`b`", "Link b")); new LinksSnippet( new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("b").description("Link b")), true) .document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description").row("`b`", "Link b")); } @Test public void presentOptionalLink() throws IOException { - this.snippets.expectLinks().withContents( - tableWithHeader("Relation", "Description").row("`foo`", "bar")); new LinksSnippet(new StubLinkExtractor().withLinks(new Link("foo", "blah")), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) .document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); } @Test public void missingOptionalLink() throws IOException { - this.snippets.expectLinks().withContents( - tableWithHeader("Relation", "Description").row("`foo`", "bar")); new LinksSnippet(new StubLinkExtractor(), Arrays.asList(new LinkDescriptor("foo").description("bar").optional())) .document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description").row("`foo`", "bar")); } @Test public void documentedLinks() throws IOException { - this.snippets.expectLinks() - .withContents(tableWithHeader("Relation", "Description").row("`a`", "one") - .row("`b`", "two")); new LinksSnippet( new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b").description("two"))) .document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description").row("`a`", "one") + .row("`b`", "two")); } @Test public void linkDescriptionFromTitleInPayload() throws IOException { - this.snippets.expectLinks() - .withContents(tableWithHeader("Relation", "Description").row("`a`", "one") - .row("`b`", "Link b")); new LinksSnippet( new StubLinkExtractor().withLinks(new Link("a", "alpha", "Link a"), new Link("b", "bravo", "Link b")), Arrays.asList(new LinkDescriptor("a").description("one"), new LinkDescriptor("b"))).document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description").row("`a`", "one") + .row("`b`", "Link b")); } @Test @@ -116,8 +116,6 @@ public class LinksSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("links")) .willReturn(snippetResource("links-with-title")); - this.snippets.expectLinks().withContents(containsString("Title for the links")); - new LinksSnippet( new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), @@ -129,6 +127,7 @@ public class LinksSnippetTests extends AbstractSnippetTests { .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) .build()); + assertThat(this.generatedSnippets.links()).contains("Title for the links"); } @Test @@ -136,10 +135,6 @@ public class LinksSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("links")) .willReturn(snippetResource("links-with-extra-column")); - this.snippets.expectLinks() - .withContents(tableWithHeader("Relation", "Description", "Foo") - .row("a", "one", "alpha").row("b", "two", "bravo")); - new LinksSnippet( new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), @@ -152,29 +147,32 @@ public class LinksSnippetTests extends AbstractSnippetTests { TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) .build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description", "Foo") + .row("a", "one", "alpha").row("b", "two", "bravo")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectLinks() - .withContents(tableWithHeader("Relation", "Description").row("`a`", "one") - .row("`b`", "two")); HypermediaDocumentation .links(new StubLinkExtractor().withLinks(new Link("a", "alpha"), new Link("b", "bravo")), new LinkDescriptor("a").description("one")) .and(new LinkDescriptor("b").description("two")) .document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description").row("`a`", "one") + .row("`b`", "two")); } @Test public void tableCellContentIsEscapedWhenNecessary() throws IOException { - this.snippets.expectLinks() - .withContents(tableWithHeader("Relation", "Description").row( - escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); new LinksSnippet(new StubLinkExtractor().withLinks(new Link("Foo|Bar", "foo")), Arrays.asList(new LinkDescriptor("Foo|Bar").description("one|two"))) .document(this.operationBuilder.build()); + assertThat(this.generatedSnippets.links()) + .is(tableWithHeader("Relation", "Description").row( + escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/ParametersTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/ParametersTests.java index 3c922886..f4eedcdc 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/ParametersTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/ParametersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,7 @@ package org.springframework.restdocs.operation; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link Parameters}. @@ -33,45 +31,45 @@ public class ParametersTests { @Test public void queryStringForNoParameters() { - assertThat(this.parameters.toQueryString(), is(equalTo(""))); + assertThat(this.parameters.toQueryString()).isEqualTo(""); } @Test public void queryStringForSingleParameter() { this.parameters.add("a", "b"); - assertThat(this.parameters.toQueryString(), is(equalTo("a=b"))); + assertThat(this.parameters.toQueryString()).isEqualTo("a=b"); } @Test public void queryStringForSingleParameterWithMultipleValues() { this.parameters.add("a", "b"); this.parameters.add("a", "c"); - assertThat(this.parameters.toQueryString(), is(equalTo("a=b&a=c"))); + assertThat(this.parameters.toQueryString()).isEqualTo("a=b&a=c"); } @Test public void queryStringForMutipleParameters() { this.parameters.add("a", "alpha"); this.parameters.add("b", "bravo"); - assertThat(this.parameters.toQueryString(), is(equalTo("a=alpha&b=bravo"))); + assertThat(this.parameters.toQueryString()).isEqualTo("a=alpha&b=bravo"); } @Test public void queryStringForParameterWithEmptyValue() { this.parameters.add("a", ""); - assertThat(this.parameters.toQueryString(), is(equalTo("a="))); + assertThat(this.parameters.toQueryString()).isEqualTo("a="); } @Test public void queryStringForParameterWithNullValue() { this.parameters.add("a", null); - assertThat(this.parameters.toQueryString(), is(equalTo("a="))); + assertThat(this.parameters.toQueryString()).isEqualTo("a="); } @Test public void queryStringForParameterThatRequiresEncoding() { this.parameters.add("a", "alpha&bravo"); - assertThat(this.parameters.toQueryString(), is(equalTo("a=alpha%26bravo"))); + assertThat(this.parameters.toQueryString()).isEqualTo("a=alpha%26bravo"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java index cf58f72e..7fcf8233 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/QueryStringParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +23,8 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertThat; /** * Tests for {@link QueryStringParser}. @@ -44,41 +42,41 @@ public class QueryStringParserTests { public void noParameters() { Parameters parameters = this.queryStringParser .parse(URI.create("http://localhost")); - assertThat(parameters.size(), is(equalTo(0))); + assertThat(parameters.size()).isEqualTo(0); } @Test public void singleParameter() { Parameters parameters = this.queryStringParser .parse(URI.create("http://localhost?a=alpha")); - assertThat(parameters.size(), is(equalTo(1))); - assertThat(parameters, hasEntry("a", Arrays.asList("alpha"))); + assertThat(parameters.size()).isEqualTo(1); + assertThat(parameters).containsEntry("a", Arrays.asList("alpha")); } @Test public void multipleParameters() { Parameters parameters = this.queryStringParser .parse(URI.create("http://localhost?a=alpha&b=bravo&c=charlie")); - assertThat(parameters.size(), is(equalTo(3))); - assertThat(parameters, hasEntry("a", Arrays.asList("alpha"))); - assertThat(parameters, hasEntry("b", Arrays.asList("bravo"))); - assertThat(parameters, hasEntry("c", Arrays.asList("charlie"))); + assertThat(parameters.size()).isEqualTo(3); + assertThat(parameters).containsEntry("a", Arrays.asList("alpha")); + assertThat(parameters).containsEntry("b", Arrays.asList("bravo")); + assertThat(parameters).containsEntry("c", Arrays.asList("charlie")); } @Test public void multipleParametersWithSameKey() { Parameters parameters = this.queryStringParser .parse(URI.create("http://localhost?a=apple&a=avocado")); - assertThat(parameters.size(), is(equalTo(1))); - assertThat(parameters, hasEntry("a", Arrays.asList("apple", "avocado"))); + assertThat(parameters.size()).isEqualTo(1); + assertThat(parameters).containsEntry("a", Arrays.asList("apple", "avocado")); } @Test public void encoded() { Parameters parameters = this.queryStringParser .parse(URI.create("http://localhost?a=al%26%3Dpha")); - assertThat(parameters.size(), is(equalTo(1))); - assertThat(parameters, hasEntry("a", Arrays.asList("al&=pha"))); + assertThat(parameters.size()).isEqualTo(1); + assertThat(parameters).containsEntry("a", Arrays.asList("al&=pha")); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java index 4e45a742..7d5ffe16 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ContentModifyingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,9 +32,7 @@ import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; import org.springframework.restdocs.operation.Parameters; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ContentModifyingOperationPreprocessor}. @@ -65,7 +63,7 @@ public class ContentModifyingOperationPreprocessorTests { new HttpHeaders(), new Parameters(), Collections.emptyList()); OperationRequest preprocessed = this.preprocessor.preprocess(request); - assertThat(preprocessed.getContent(), is(equalTo("modified".getBytes()))); + assertThat(preprocessed.getContent()).isEqualTo("modified".getBytes()); } @Test @@ -73,7 +71,7 @@ public class ContentModifyingOperationPreprocessorTests { OperationResponse response = this.responseFactory.create(HttpStatus.OK, new HttpHeaders(), "content".getBytes()); OperationResponse preprocessed = this.preprocessor.preprocess(response); - assertThat(preprocessed.getContent(), is(equalTo("modified".getBytes()))); + assertThat(preprocessed.getContent()).isEqualTo("modified".getBytes()); } @Test @@ -85,7 +83,7 @@ public class ContentModifyingOperationPreprocessorTests { httpHeaders, new Parameters(), Collections.emptyList()); OperationRequest preprocessed = this.preprocessor.preprocess(request); - assertThat(preprocessed.getHeaders().getContentLength(), is(equalTo(8L))); + assertThat(preprocessed.getHeaders().getContentLength()).isEqualTo(8L); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java index 62e69a36..6f2d40ac 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationRequestPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.restdocs.operation.OperationRequest; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -54,7 +53,7 @@ public class DelegatingOperationRequestPreprocessorTests { Arrays.asList(preprocessor1, preprocessor2, preprocessor3)) .preprocess(originalRequest); - assertThat(result, is(preprocessedRequest3)); + assertThat(result).isSameAs(preprocessedRequest3); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java index dc1a9719..7678200d 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/DelegatingOperationResponsePreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,7 @@ import org.junit.Test; import org.springframework.restdocs.operation.OperationResponse; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -55,7 +54,7 @@ public class DelegatingOperationResponsePreprocessorTests { Arrays.asList(preprocessor1, preprocessor2, preprocessor3)) .preprocess(originalResponse); - assertThat(result, is(preprocessedResponse3)); + assertThat(result).isSameAs(preprocessedResponse3); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java index ca13f47b..5610e0f3 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/HeaderRemovingOperationPreprocessorTests.java @@ -32,10 +32,7 @@ import org.springframework.restdocs.operation.OperationResponse; import org.springframework.restdocs.operation.OperationResponseFactory; import org.springframework.restdocs.operation.Parameters; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link HeaderRemovingOperationPreprocessorTests}. @@ -59,18 +56,18 @@ public class HeaderRemovingOperationPreprocessorTests { getHttpHeaders(), new Parameters(), Collections.emptyList()); OperationRequest preprocessed = this.preprocessor.preprocess(request); - assertThat(preprocessed.getHeaders().size(), is(equalTo(2))); - assertThat(preprocessed.getHeaders(), hasEntry("a", Arrays.asList("alpha"))); - assertThat(preprocessed.getHeaders(), - hasEntry("Host", Arrays.asList("localhost"))); + assertThat(preprocessed.getHeaders().size()).isEqualTo(2); + assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha")); + assertThat(preprocessed.getHeaders()).containsEntry("Host", + Arrays.asList("localhost")); } @Test public void modifyResponseHeaders() { OperationResponse response = createResponse(); OperationResponse preprocessed = this.preprocessor.preprocess(response); - assertThat(preprocessed.getHeaders().size(), is(equalTo(1))); - assertThat(preprocessed.getHeaders(), hasEntry("a", Arrays.asList("alpha"))); + assertThat(preprocessed.getHeaders().size()).isEqualTo(1); + assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha")); } @Test @@ -79,10 +76,10 @@ public class HeaderRemovingOperationPreprocessorTests { HeaderRemovingOperationPreprocessor processor = new HeaderRemovingOperationPreprocessor( new PatternMatchHeaderFilter("co.*le(.)gth]")); OperationResponse preprocessed = processor.preprocess(response); - assertThat(preprocessed.getHeaders().size(), is(equalTo(2))); - assertThat(preprocessed.getHeaders(), hasEntry("a", Arrays.asList("alpha"))); - assertThat(preprocessed.getHeaders(), - hasEntry("b", Arrays.asList("bravo", "banana"))); + assertThat(preprocessed.getHeaders().size()).isEqualTo(2); + assertThat(preprocessed.getHeaders()).containsEntry("a", Arrays.asList("alpha")); + assertThat(preprocessed.getHeaders()).containsEntry("b", + Arrays.asList("bravo", "banana")); } @Test @@ -90,7 +87,7 @@ public class HeaderRemovingOperationPreprocessorTests { HeaderRemovingOperationPreprocessor processor = new HeaderRemovingOperationPreprocessor( new PatternMatchHeaderFilter(".*")); OperationResponse preprocessed = processor.preprocess(createResponse()); - assertThat(preprocessed.getHeaders().size(), is(equalTo(0))); + assertThat(preprocessed.getHeaders().size()).isEqualTo(0); } private OperationResponse createResponse(String... extraHeaders) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java index 09c6affa..2d9b115e 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/LinkMaskingContentModifierTests.java @@ -30,9 +30,7 @@ import org.junit.Test; import org.springframework.restdocs.hypermedia.Link; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LinkMaskingContentModifier}. @@ -53,39 +51,36 @@ public class LinkMaskingContentModifierTests { @Test public void halLinksAreMasked() throws Exception { assertThat( - this.contentModifier.modifyContent(halPayloadWithLinks(this.links), null), - is(equalTo(halPayloadWithLinks(this.maskedLinks)))); + this.contentModifier.modifyContent(halPayloadWithLinks(this.links), null)) + .isEqualTo(halPayloadWithLinks(this.maskedLinks)); } @Test public void formattedHalLinksAreMasked() throws Exception { - assertThat( - this.contentModifier - .modifyContent(formattedHalPayloadWithLinks(this.links), null), - is(equalTo(formattedHalPayloadWithLinks(this.maskedLinks)))); + assertThat(this.contentModifier + .modifyContent(formattedHalPayloadWithLinks(this.links), null)) + .isEqualTo(formattedHalPayloadWithLinks(this.maskedLinks)); } @Test public void atomLinksAreMasked() throws Exception { assertThat(this.contentModifier.modifyContent(atomPayloadWithLinks(this.links), - null), is(equalTo(atomPayloadWithLinks(this.maskedLinks)))); + null)).isEqualTo(atomPayloadWithLinks(this.maskedLinks)); } @Test public void formattedAtomLinksAreMasked() throws Exception { - assertThat( - this.contentModifier - .modifyContent(formattedAtomPayloadWithLinks(this.links), null), - is(equalTo(formattedAtomPayloadWithLinks(this.maskedLinks)))); + assertThat(this.contentModifier + .modifyContent(formattedAtomPayloadWithLinks(this.links), null)) + .isEqualTo(formattedAtomPayloadWithLinks(this.maskedLinks)); } @Test public void maskCanBeCustomized() throws Exception { - assertThat( - new LinkMaskingContentModifier("custom") - .modifyContent(formattedAtomPayloadWithLinks(this.links), null), - is(equalTo(formattedAtomPayloadWithLinks(new Link("a", "custom"), - new Link("b", "custom"))))); + assertThat(new LinkMaskingContentModifier("custom") + .modifyContent(formattedAtomPayloadWithLinks(this.links), null)) + .isEqualTo(formattedAtomPayloadWithLinks(new Link("a", "custom"), + new Link("b", "custom"))); } private byte[] atomPayloadWithLinks(Link... links) throws JsonProcessingException { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java index ebcef8ce..9c862a35 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/ParametersModifyingOperationPreprocessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.restdocs.operation.preprocess; import java.net.URI; +import java.util.Arrays; import java.util.Collections; import org.junit.Test; @@ -28,11 +29,7 @@ import org.springframework.restdocs.operation.OperationRequestFactory; import org.springframework.restdocs.operation.OperationRequestPart; import org.springframework.restdocs.operation.Parameters; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ParametersModifyingOperationPreprocessor}. @@ -47,63 +44,58 @@ public class ParametersModifyingOperationPreprocessorTests { public void addNewParameter() { Parameters parameters = new Parameters(); assertThat(this.preprocessor.add("a", "alpha") - .preprocess(createRequest(parameters)).getParameters(), - hasEntry(equalTo("a"), contains("alpha"))); + .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", + Arrays.asList("alpha")); } @Test public void addValueToExistingParameter() { Parameters parameters = new Parameters(); parameters.add("a", "apple"); - assertThat( - this.preprocessor.add("a", "alpha").preprocess(createRequest(parameters)) - .getParameters(), - hasEntry(equalTo("a"), contains("apple", "alpha"))); + assertThat(this.preprocessor.add("a", "alpha") + .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", + Arrays.asList("apple", "alpha")); } @Test public void setNewParameter() { Parameters parameters = new Parameters(); - assertThat( - this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createRequest(parameters)).getParameters(), - hasEntry(equalTo("a"), contains("alpha", "avocado"))); + assertThat(this.preprocessor.set("a", "alpha", "avocado") + .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", + Arrays.asList("alpha", "avocado")); } @Test public void setExistingParameter() { Parameters parameters = new Parameters(); parameters.add("a", "apple"); - assertThat( - this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createRequest(parameters)).getParameters(), - hasEntry(equalTo("a"), contains("alpha", "avocado"))); + assertThat(this.preprocessor.set("a", "alpha", "avocado") + .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", + Arrays.asList("alpha", "avocado")); } @Test public void removeNonExistentParameter() { Parameters parameters = new Parameters(); assertThat(this.preprocessor.remove("a").preprocess(createRequest(parameters)) - .getParameters().size(), is(equalTo(0))); + .getParameters().size()).isEqualTo(0); } @Test public void removeParameter() { Parameters parameters = new Parameters(); parameters.add("a", "apple"); - assertThat( - this.preprocessor.set("a", "alpha", "avocado") - .preprocess(createRequest(parameters)).getParameters(), - hasEntry(equalTo("a"), contains("alpha", "avocado"))); + assertThat(this.preprocessor.set("a", "alpha", "avocado") + .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", + Arrays.asList("alpha", "avocado")); } @Test public void removeParameterValueForNonExistentParameter() { Parameters parameters = new Parameters(); - assertThat( - this.preprocessor.remove("a", "apple") - .preprocess(createRequest(parameters)).getParameters().size(), - is(equalTo(0))); + assertThat(this.preprocessor.remove("a", "apple") + .preprocess(createRequest(parameters)).getParameters().size()) + .isEqualTo(0); } @Test @@ -111,20 +103,18 @@ public class ParametersModifyingOperationPreprocessorTests { Parameters parameters = new Parameters(); parameters.add("a", "apple"); parameters.add("a", "alpha"); - assertThat( - this.preprocessor.remove("a", "apple") - .preprocess(createRequest(parameters)).getParameters(), - hasEntry(equalTo("a"), contains("alpha"))); + assertThat(this.preprocessor.remove("a", "apple") + .preprocess(createRequest(parameters)).getParameters()).containsEntry("a", + Arrays.asList("alpha")); } @Test public void removeParameterValueWithSingleValueRemovesEntryEntirely() { Parameters parameters = new Parameters(); parameters.add("a", "apple"); - assertThat( - this.preprocessor.remove("a", "apple") - .preprocess(createRequest(parameters)).getParameters().size(), - is(equalTo(0))); + assertThat(this.preprocessor.remove("a", "apple") + .preprocess(createRequest(parameters)).getParameters().size()) + .isEqualTo(0); } private OperationRequest createRequest(Parameters parameters) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java index f8ea398d..5742e482 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PatternReplacingContentModifierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +23,12 @@ import org.junit.Test; import org.springframework.http.MediaType; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link PatternReplacingContentModifier}. * * @author Andy Wilkinson - * */ public class PatternReplacingContentModifierTests { @@ -43,8 +40,8 @@ public class PatternReplacingContentModifierTests { PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier( pattern, "<>"); assertThat(contentModifier.modifyContent( - "{\"id\" : \"CA761232-ED42-11CE-BACD-00AA0057B223\"}".getBytes(), null), - is(equalTo("{\"id\" : \"<>\"}".getBytes()))); + "{\"id\" : \"CA761232-ED42-11CE-BACD-00AA0057B223\"}".getBytes(), null)) + .isEqualTo("{\"id\" : \"<>\"}".getBytes()); } @Test @@ -54,10 +51,9 @@ public class PatternReplacingContentModifierTests { Pattern.CASE_INSENSITIVE); PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier( pattern, "<>"); - assertThat( - contentModifier.modifyContent( - "{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes(), null), - is(equalTo("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes()))); + assertThat(contentModifier + .modifyContent("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes(), null)) + .isEqualTo("{\"id\" : \"CA76-ED42-11CE-BACD\"}".getBytes()); } @Test @@ -66,10 +62,9 @@ public class PatternReplacingContentModifierTests { Pattern pattern = Pattern.compile("[0-9]+"); PatternReplacingContentModifier contentModifier = new PatternReplacingContentModifier( pattern, "<>"); - assertThat( - contentModifier.modifyContent((japaneseContent + " 123").getBytes(), - new MediaType("text", "plain", Charset.forName("UTF-8"))), - is(equalTo((japaneseContent + " <>").getBytes()))); + assertThat(contentModifier.modifyContent((japaneseContent + " 123").getBytes(), + new MediaType("text", "plain", Charset.forName("UTF-8")))) + .isEqualTo((japaneseContent + " <>").getBytes()); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java index 132b4c49..9d8b8ed6 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/PrettyPrintingContentModifierTests.java @@ -25,10 +25,8 @@ import org.junit.Test; import org.springframework.restdocs.test.OutputCapture; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.isEmptyString; -import static org.junit.Assert.assertThat; /** * Tests for {@link PrettyPrintingContentModifier}. @@ -44,25 +42,23 @@ public class PrettyPrintingContentModifierTests { @Test public void prettyPrintJson() throws Exception { assertThat(new PrettyPrintingContentModifier() - .modifyContent("{\"a\":5}".getBytes(), null), - equalTo(String.format("{%n \"a\" : 5%n}").getBytes())); + .modifyContent("{\"a\":5}".getBytes(), null)) + .isEqualTo(String.format("{%n \"a\" : 5%n}").getBytes()); } @Test public void prettyPrintXml() throws Exception { - assertThat( - new PrettyPrintingContentModifier().modifyContent( - "".getBytes(), null), - equalTo(String - .format("%n" + assertThat(new PrettyPrintingContentModifier().modifyContent( + "".getBytes(), null)).isEqualTo( + String.format("%n" + "%n %n%n") - .getBytes())); + .getBytes()); } @Test public void empytContentIsHandledGracefully() throws Exception { - assertThat(new PrettyPrintingContentModifier().modifyContent("".getBytes(), null), - equalTo("".getBytes())); + assertThat(new PrettyPrintingContentModifier().modifyContent("".getBytes(), null)) + .isEqualTo("".getBytes()); } @Test @@ -70,7 +66,7 @@ public class PrettyPrintingContentModifierTests { String content = "abcdefg"; this.outputCapture.expect(isEmptyString()); assertThat(new PrettyPrintingContentModifier().modifyContent(content.getBytes(), - null), equalTo(content.getBytes())); + null)).isEqualTo(content.getBytes()); } @@ -83,7 +79,7 @@ public class PrettyPrintingContentModifierTests { Map output = objectMapper .readValue(new PrettyPrintingContentModifier().modifyContent( objectMapper.writeValueAsBytes(input), null), Map.class); - assertThat(output, is(equalTo(input))); + assertThat(output).isEqualTo(input); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java index 1907cf49..0ab56170 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/operation/preprocess/UriModifyingOperationPreprocessorTests.java @@ -35,9 +35,7 @@ import org.springframework.restdocs.operation.OperationResponseFactory; import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestCookie; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link UriModifyingOperationPreprocessor}. @@ -57,8 +55,7 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://localhost:12345")); - assertThat(processed.getUri(), - is(equalTo(URI.create("https://localhost:12345")))); + assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345")); } @Test @@ -66,10 +63,10 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.host("api.example.com"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.foo.com:12345")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com:12345")))); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST), - is(equalTo("api.example.com:12345"))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com:12345")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)) + .isEqualTo("api.example.com:12345"); } @Test @@ -77,10 +74,10 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com:23456")))); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST), - is(equalTo("api.example.com:23456"))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com:23456")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)) + .isEqualTo("api.example.com:23456"); } @Test @@ -88,9 +85,9 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345")); - assertThat(processed.getUri(), is(equalTo(URI.create("http://api.example.com")))); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST), - is(equalTo("api.example.com"))); + assertThat(processed.getUri()).isEqualTo(URI.create("http://api.example.com")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)) + .isEqualTo("api.example.com"); } @Test @@ -98,8 +95,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345/foo/bar")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com/foo/bar")))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com/foo/bar")); } @Test @@ -107,8 +104,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345?foo=bar")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com?foo=bar")))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com?foo=bar")); } @Test @@ -116,8 +113,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345#foo")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com#foo")))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com#foo")); } @Test @@ -126,8 +123,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'https://localhost:12345' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'https://localhost:12345' should be used"); } @Test @@ -136,8 +133,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://api.example.com:12345' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://api.example.com:12345' should be used"); } @Test @@ -146,8 +143,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost:23456' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost:23456' should be used"); } @Test @@ -156,8 +153,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost' should be used"); } @Test @@ -166,8 +163,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); - assertThat(new String(processed.getContent()), is(equalTo( - "Use 'http://localhost' or 'https://localhost' to access the service"))); + assertThat(new String(processed.getContent())).isEqualTo( + "Use 'http://localhost' or 'https://localhost' to access the service"); } @Test @@ -176,8 +173,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345/foo/bar' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost/foo/bar' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost/foo/bar' should be used"); } @Test @@ -186,8 +183,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345?foo=bar' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost?foo=bar' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost?foo=bar' should be used"); } @Test @@ -196,8 +193,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345#foo' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost#foo' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost#foo' should be used"); } @Test @@ -206,8 +203,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'https://localhost:12345' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'https://localhost:12345' should be used"); } @Test @@ -216,8 +213,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://api.example.com:12345' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://api.example.com:12345' should be used"); } @Test @@ -226,8 +223,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost:23456' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost:23456' should be used"); } @Test @@ -236,8 +233,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost' should be used"); } @Test @@ -246,8 +243,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); - assertThat(new String(processed.getContent()), is(equalTo( - "Use 'http://localhost' or 'https://localhost' to access the service"))); + assertThat(new String(processed.getContent())).isEqualTo( + "Use 'http://localhost' or 'https://localhost' to access the service"); } @Test @@ -256,8 +253,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345/foo/bar' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost/foo/bar' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost/foo/bar' should be used"); } @Test @@ -266,8 +263,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345?foo=bar' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost?foo=bar' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost?foo=bar' should be used"); } @Test @@ -276,34 +273,33 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345#foo' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost#foo' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost#foo' should be used"); } @Test public void urisInRequestHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") .preprocess(createRequestWithHeader("Foo", "http://locahost:12345")); - assertThat(processed.getHeaders().getFirst("Foo"), - is(equalTo("http://api.example.com:12345"))); - assertThat(processed.getHeaders().getFirst("Host"), - is(equalTo("api.example.com"))); + assertThat(processed.getHeaders().getFirst("Foo")) + .isEqualTo("http://api.example.com:12345"); + assertThat(processed.getHeaders().getFirst("Host")).isEqualTo("api.example.com"); } @Test public void urisInResponseHeadersCanBeModified() { OperationResponse processed = this.preprocessor.host("api.example.com") .preprocess(createResponseWithHeader("Foo", "http://locahost:12345")); - assertThat(processed.getHeaders().getFirst("Foo"), - is(equalTo("http://api.example.com:12345"))); + assertThat(processed.getHeaders().getFirst("Foo")) + .isEqualTo("http://api.example.com:12345"); } @Test public void urisInRequestPartHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com").preprocess( createRequestWithPartWithHeader("Foo", "http://locahost:12345")); - assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo"), - is(equalTo("http://api.example.com:12345"))); + assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo")) + .isEqualTo("http://api.example.com:12345"); } @Test @@ -311,8 +307,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.host("api.example.com") .preprocess(createRequestWithPartWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getParts().iterator().next().getContent()), - is(equalTo("The uri 'http://api.example.com:12345' should be used"))); + assertThat(new String(processed.getParts().iterator().next().getContent())) + .isEqualTo("The uri 'http://api.example.com:12345' should be used"); } @Test @@ -320,8 +316,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); - assertThat(processed.getUri(), - is(equalTo(URI.create("https://localhost:12345?foo=%7B%7D")))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); } @@ -333,7 +329,7 @@ public class UriModifyingOperationPreprocessorTests { new HttpHeaders(), new Parameters(), Collections.emptyList(), cookies); OperationRequest processed = this.preprocessor.preprocess(request); - assertThat(processed.getCookies().size(), is(equalTo(1))); + assertThat(processed.getCookies().size()).isEqualTo(1); } private OperationRequest createRequestWithUri(String uri) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java index 9f737e3a..1ce44f4b 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/AsciidoctorRequestFieldsSnippetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,14 +26,15 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.restdocs.templates.TemplateEngine; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import org.springframework.restdocs.test.ExpectedSnippets; +import org.springframework.restdocs.test.GeneratedSnippets; import org.springframework.restdocs.test.OperationBuilder; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor; -import static org.springframework.restdocs.test.SnippetMatchers.tableWithHeader; +import static org.springframework.restdocs.test.SnippetConditions.tableWithHeader; /** * Tests for {@link RequestFieldsSnippet} that are specific to Asciidoctor. @@ -46,19 +47,13 @@ public class AsciidoctorRequestFieldsSnippetTests { public OperationBuilder operationBuilder = new OperationBuilder(asciidoctor()); @Rule - public ExpectedSnippets snippets = new ExpectedSnippets(asciidoctor()); + public GeneratedSnippets generatedSnippets = new GeneratedSnippets(asciidoctor()); @Test public void requestFieldsWithListDescription() throws IOException { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) .willReturn(snippetResource("request-fields-with-list-description")); - this.snippets.expectRequestFields().withContents( - tableWithHeader(asciidoctor(), "Path", "Type", "Description") - // - .row("a", "String", String.format(" - one%n - two")) - .configuration("[cols=\"1,1,1a\"]")); - new RequestFieldsSnippet( Arrays.asList( fieldWithPath("a").description(Arrays.asList("one", "two")))) @@ -69,6 +64,11 @@ public class AsciidoctorRequestFieldsSnippetTests { resolver)) .request("http://localhost") .content("{\"a\": \"foo\"}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader(asciidoctor(), "Path", "Type", "Description") + // + .row("a", "String", String.format(" - one%n - two")) + .configuration("[cols=\"1,1,1a\"]")); } private FileSystemResource snippetResource(String name) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java index eabc887a..42c7ae07 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/FieldPathPayloadSubsectionExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,9 +29,8 @@ import org.junit.rules.ExpectedException; import org.springframework.http.MediaType; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; /** * Tests for {@link FieldPathPayloadSubsectionExtractor}. @@ -52,8 +51,8 @@ public class FieldPathPayloadSubsectionExtractorTests { MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); - assertThat(extracted.size(), is(equalTo(1))); - assertThat(extracted.get("c"), is(equalTo((Object) 5))); + assertThat(extracted.size()).isEqualTo(1); + assertThat(extracted.get("c")).isEqualTo(5); } @Test @@ -65,9 +64,9 @@ public class FieldPathPayloadSubsectionExtractorTests { MediaType.APPLICATION_JSON); List> extracted = new ObjectMapper() .readValue(extractedPayload, List.class); - assertThat(extracted.size(), is(equalTo(2))); - assertThat(extracted.get(0).get("b"), is(equalTo((Object) 5))); - assertThat(extracted.get(1).get("b"), is(equalTo((Object) 4))); + assertThat(extracted.size()).isEqualTo(2); + assertThat(extracted.get(0).get("b")).isEqualTo(5); + assertThat(extracted.get(1).get("b")).isEqualTo(4); } @Test @@ -79,8 +78,8 @@ public class FieldPathPayloadSubsectionExtractorTests { MediaType.APPLICATION_JSON); List> extracted = new ObjectMapper() .readValue(extractedPayload, List.class); - assertThat(extracted.size(), is(equalTo(1))); - assertThat(extracted.get(0).get("b"), is(equalTo((Object) 5))); + assertThat(extracted.size()).isEqualTo(1); + assertThat(extracted.get(0).get("b")).isEqualTo(5); } @Test @@ -92,8 +91,8 @@ public class FieldPathPayloadSubsectionExtractorTests { MediaType.APPLICATION_JSON); Map extracted = new ObjectMapper().readValue(extractedPayload, Map.class); - assertThat(extracted.size(), is(equalTo(1))); - assertThat(extracted.get("c"), is(equalTo((Object) 5))); + assertThat(extracted.size()).isEqualTo(1); + assertThat(extracted.get("c")).isEqualTo(5); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java index dd043a23..bfb6eb8f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonContentHandlerTests.java @@ -23,9 +23,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JsonContentHandler}. @@ -65,7 +63,7 @@ public class JsonContentHandlerTests { Object fieldType = new JsonContentHandler( "{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes()) .determineFieldType(new FieldDescriptor("a[].id").optional()); - assertThat((JsonFieldType) fieldType, is(equalTo(JsonFieldType.NUMBER))); + assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER); } @Test @@ -73,7 +71,7 @@ public class JsonContentHandlerTests { Object fieldType = new JsonContentHandler( "{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes()) .determineFieldType(new FieldDescriptor("a[].id").optional()); - assertThat((JsonFieldType) fieldType, is(equalTo(JsonFieldType.NUMBER))); + assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.NUMBER); } @Test @@ -81,7 +79,7 @@ public class JsonContentHandlerTests { Object fieldType = new JsonContentHandler( "{\"a\":[{\"id\":1},{\"id\":null}]}\"".getBytes()) .determineFieldType(new FieldDescriptor("a[].id")); - assertThat((JsonFieldType) fieldType, is(equalTo(JsonFieldType.VARIES))); + assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.VARIES); } @Test @@ -89,7 +87,7 @@ public class JsonContentHandlerTests { Object fieldType = new JsonContentHandler( "{\"a\":[{\"id\":null},{\"id\":1}]}".getBytes()) .determineFieldType(new FieldDescriptor("a[].id")); - assertThat((JsonFieldType) fieldType, is(equalTo(JsonFieldType.VARIES))); + assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.VARIES); } @Test @@ -97,7 +95,7 @@ public class JsonContentHandlerTests { Object fieldType = new JsonContentHandler("{\"a\": null}".getBytes()) .determineFieldType( new FieldDescriptor("a").type(JsonFieldType.STRING).optional()); - assertThat((JsonFieldType) fieldType, is(equalTo(JsonFieldType.STRING))); + assertThat((JsonFieldType) fieldType).isEqualTo(JsonFieldType.STRING); } @Test @@ -112,8 +110,8 @@ public class JsonContentHandlerTests { "{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes()) .findMissingFields(Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), new FieldDescriptor("c"))); - assertThat(missingFields.size(), is(equalTo(1))); - assertThat(missingFields.get(0).getPath(), is(equalTo("c"))); + assertThat(missingFields.size()).isEqualTo(1); + assertThat(missingFields.get(0).getPath()).isEqualTo("c"); } @Test @@ -122,7 +120,7 @@ public class JsonContentHandlerTests { "{\"a\": \"alpha\", \"b\":\"bravo\"}".getBytes()).findMissingFields( Arrays.asList(new FieldDescriptor("a"), new FieldDescriptor("b"), new FieldDescriptor("c").optional())); - assertThat(missingFields.size(), is(equalTo(0))); + assertThat(missingFields.size()).isEqualTo(0); } @Test @@ -131,8 +129,8 @@ public class JsonContentHandlerTests { "{\"a\":\"alpha\",\"b\":\"bravo\"}".getBytes()).findMissingFields( Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"), new FieldDescriptor("a.c"))); - assertThat(missingFields.size(), is(equalTo(1))); - assertThat(missingFields.get(0).getPath(), is(equalTo("a.c"))); + assertThat(missingFields.size()).isEqualTo(1); + assertThat(missingFields.get(0).getPath()).isEqualTo("a.c"); } @Test @@ -141,7 +139,7 @@ public class JsonContentHandlerTests { "{\"b\":\"bravo\"}".getBytes()).findMissingFields( Arrays.asList(new FieldDescriptor("a").optional(), new FieldDescriptor("b"), new FieldDescriptor("a.c"))); - assertThat(missingFields.size(), is(equalTo(0))); + assertThat(missingFields.size()).isEqualTo(0); } @Test @@ -151,7 +149,7 @@ public class JsonContentHandlerTests { .findMissingFields(Arrays.asList(new FieldDescriptor("outer"), new FieldDescriptor("outer[]").optional(), new FieldDescriptor("outer[].inner"))); - assertThat(missingFields.size(), is(equalTo(0))); + assertThat(missingFields.size()).isEqualTo(0); } @Test @@ -161,7 +159,7 @@ public class JsonContentHandlerTests { .getBytes()).findMissingFields( Arrays.asList(new FieldDescriptor("a.[].c").optional(), new FieldDescriptor("a.[].c.d"))); - assertThat(missingFields.size(), is(equalTo(0))); + assertThat(missingFields.size()).isEqualTo(0); } @Test @@ -171,7 +169,7 @@ public class JsonContentHandlerTests { Arrays.asList(new FieldDescriptor("a.[].b").optional(), new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c"))); - assertThat(missingFields.size(), is(equalTo(0))); + assertThat(missingFields.size()).isEqualTo(0); } @Test @@ -181,8 +179,8 @@ public class JsonContentHandlerTests { Arrays.asList(new FieldDescriptor("a.[].b").optional(), new FieldDescriptor("a.[].b.[]").optional(), new FieldDescriptor("a.[].b.[].c"))); - assertThat(missingFields.size(), is(equalTo(1))); - assertThat(missingFields.get(0).getPath(), is(equalTo("a.[].b.[].c"))); + assertThat(missingFields.size()).isEqualTo(1); + assertThat(missingFields.get(0).getPath()).isEqualTo("a.[].b.[].c"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java index b0762d7f..8447e63f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,7 @@ import org.junit.Test; import org.springframework.restdocs.payload.JsonFieldPath.PathType; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JsonFieldPath}. @@ -36,137 +33,138 @@ public class JsonFieldPathTests { @Test public void pathTypeOfSingleFieldIsSingle() { JsonFieldPath path = JsonFieldPath.compile("a"); - assertThat(path.getType(), is(equalTo(PathType.SINGLE))); + assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test public void pathTypeOfSingleNestedFieldIsSingle() { JsonFieldPath path = JsonFieldPath.compile("a.b"); - assertThat(path.getType(), is(equalTo(PathType.SINGLE))); + assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test public void pathTypeOfTopLevelArrayIsSingle() { JsonFieldPath path = JsonFieldPath.compile("[]"); - assertThat(path.getType(), is(equalTo(PathType.SINGLE))); + assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test public void pathTypeOfFieldBeneathTopLevelArrayIsMulti() { JsonFieldPath path = JsonFieldPath.compile("[]a"); - assertThat(path.getType(), is(equalTo(PathType.MULTI))); + assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test public void pathTypeOfSingleNestedArrayIsSingle() { JsonFieldPath path = JsonFieldPath.compile("a[]"); - assertThat(path.getType(), is(equalTo(PathType.SINGLE))); + assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test public void pathTypeOfArrayBeneathNestedFieldsIsSingle() { JsonFieldPath path = JsonFieldPath.compile("a.b[]"); - assertThat(path.getType(), is(equalTo(PathType.SINGLE))); + assertThat(path.getType()).isEqualTo(PathType.SINGLE); } @Test public void pathTypeOfArrayOfArraysIsMulti() { JsonFieldPath path = JsonFieldPath.compile("a[][]"); - assertThat(path.getType(), is(equalTo(PathType.MULTI))); + assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test public void pathTypeOfFieldBeneathAnArrayIsMulti() { JsonFieldPath path = JsonFieldPath.compile("a[].b"); - assertThat(path.getType(), is(equalTo(PathType.MULTI))); + assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test public void pathTypeOfFieldBeneathTopLevelWildcardIsMulti() { JsonFieldPath path = JsonFieldPath.compile("*.a"); - assertThat(path.getType(), is(equalTo(PathType.MULTI))); + assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test public void pathTypeOfFieldBeneathNestedWildcardIsMulti() { JsonFieldPath path = JsonFieldPath.compile("a.*.b"); - assertThat(path.getType(), is(equalTo(PathType.MULTI))); + assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test public void pathTypeOfLeafWidlcardIsMulti() { JsonFieldPath path = JsonFieldPath.compile("a.*"); - assertThat(path.getType(), is(equalTo(PathType.MULTI))); + assertThat(path.getType()).isEqualTo(PathType.MULTI); } @Test public void compilationOfSingleElementPath() { - assertThat(JsonFieldPath.compile("a").getSegments(), contains("a")); + assertThat(JsonFieldPath.compile("a").getSegments()).containsExactly("a"); } @Test public void compilationOfMultipleElementPath() { - assertThat(JsonFieldPath.compile("a.b.c").getSegments(), contains("a", "b", "c")); + assertThat(JsonFieldPath.compile("a.b.c").getSegments()).containsExactly("a", "b", + "c"); } @Test public void compilationOfPathWithArraysWithNoDotSeparators() { - assertThat(JsonFieldPath.compile("a[]b[]c").getSegments(), - contains("a", "[]", "b", "[]", "c")); + assertThat(JsonFieldPath.compile("a[]b[]c").getSegments()).containsExactly("a", + "[]", "b", "[]", "c"); } @Test public void compilationOfPathWithArraysWithPreAndPostDotSeparators() { - assertThat(JsonFieldPath.compile("a.[].b.[].c").getSegments(), - contains("a", "[]", "b", "[]", "c")); + assertThat(JsonFieldPath.compile("a.[].b.[].c").getSegments()) + .containsExactly("a", "[]", "b", "[]", "c"); } @Test public void compilationOfPathWithArraysWithPreDotSeparators() { - assertThat(JsonFieldPath.compile("a.[]b.[]c").getSegments(), - contains("a", "[]", "b", "[]", "c")); + assertThat(JsonFieldPath.compile("a.[]b.[]c").getSegments()).containsExactly("a", + "[]", "b", "[]", "c"); } @Test public void compilationOfPathWithArraysWithPostDotSeparators() { - assertThat(JsonFieldPath.compile("a[].b[].c").getSegments(), - contains("a", "[]", "b", "[]", "c")); + assertThat(JsonFieldPath.compile("a[].b[].c").getSegments()).containsExactly("a", + "[]", "b", "[]", "c"); } @Test public void compilationOfPathStartingWithAnArray() { - assertThat(JsonFieldPath.compile("[]a.b.c").getSegments(), - contains("[]", "a", "b", "c")); + assertThat(JsonFieldPath.compile("[]a.b.c").getSegments()).containsExactly("[]", + "a", "b", "c"); } @Test public void compilationOfMultipleElementPathWithBrackets() { - assertThat(JsonFieldPath.compile("['a']['b']['c']").getSegments(), - contains("a", "b", "c")); + assertThat(JsonFieldPath.compile("['a']['b']['c']").getSegments()) + .containsExactly("a", "b", "c"); } @Test public void compilationOfMultipleElementPathWithAndWithoutBrackets() { - assertThat(JsonFieldPath.compile("['a'][].b['c']").getSegments(), - contains("a", "[]", "b", "c")); + assertThat(JsonFieldPath.compile("['a'][].b['c']").getSegments()) + .containsExactly("a", "[]", "b", "c"); } @Test public void compilationOfMultipleElementPathWithAndWithoutBracketsAndEmbeddedDots() { - assertThat(JsonFieldPath.compile("['a.key'][].b['c']").getSegments(), - contains("a.key", "[]", "b", "c")); + assertThat(JsonFieldPath.compile("['a.key'][].b['c']").getSegments()) + .containsExactly("a.key", "[]", "b", "c"); } @Test public void compilationOfPathWithAWildcard() { - assertThat(JsonFieldPath.compile("a.b.*.c").getSegments(), - contains("a", "b", "*", "c")); + assertThat(JsonFieldPath.compile("a.b.*.c").getSegments()).containsExactly("a", + "b", "*", "c"); } @Test public void compilationOfPathWithAWildcardInBrackets() { - assertThat(JsonFieldPath.compile("a.b.['*'].c").getSegments(), - contains("a", "b", "*", "c")); + assertThat(JsonFieldPath.compile("a.b.['*'].c").getSegments()) + .containsExactly("a", "b", "*", "c"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java index a9a81e69..c8733b81 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,13 +28,7 @@ import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.hasEntry; -import static org.hamcrest.Matchers.hasKey; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JsonFieldProcessor}. @@ -49,8 +43,8 @@ public class JsonFieldProcessorTests { public void extractTopLevelMapEntry() { Map payload = new HashMap<>(); payload.put("a", "alpha"); - assertThat(this.fieldProcessor.extract("a", payload).getValue(), - equalTo((Object) "alpha")); + assertThat(this.fieldProcessor.extract("a", payload).getValue()) + .isEqualTo("alpha"); } @Test @@ -59,8 +53,8 @@ public class JsonFieldProcessorTests { Map alpha = new HashMap<>(); payload.put("a", alpha); alpha.put("b", "bravo"); - assertThat(this.fieldProcessor.extract("a.b", payload).getValue(), - equalTo((Object) "bravo")); + assertThat(this.fieldProcessor.extract("a.b", payload).getValue()) + .isEqualTo("bravo"); } @Test @@ -70,8 +64,8 @@ public class JsonFieldProcessorTests { bravo.put("b", "bravo"); payload.add(bravo); payload.add(bravo); - assertThat(this.fieldProcessor.extract("[]", payload).getValue(), - equalTo((Object) payload)); + assertThat(this.fieldProcessor.extract("[]", payload).getValue()) + .isEqualTo(payload); } @Test @@ -81,8 +75,7 @@ public class JsonFieldProcessorTests { bravo.put("b", "bravo"); List> alpha = Arrays.asList(bravo, bravo); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a", payload).getValue(), - equalTo((Object) alpha)); + assertThat(this.fieldProcessor.extract("a", payload).getValue()).isEqualTo(alpha); } @Test @@ -92,8 +85,8 @@ public class JsonFieldProcessorTests { bravo.put("b", "bravo"); List> alpha = Arrays.asList(bravo, bravo); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[]", payload).getValue(), - equalTo((Object) alpha)); + assertThat(this.fieldProcessor.extract("a[]", payload).getValue()) + .isEqualTo(alpha); } @Test @@ -103,8 +96,8 @@ public class JsonFieldProcessorTests { entry.put("b", "bravo"); List> alpha = Arrays.asList(entry, entry); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[].b", payload).getValue(), - equalTo((Object) Arrays.asList("bravo", "bravo"))); + assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()) + .isEqualTo(Arrays.asList("bravo", "bravo")); } @Test @@ -115,8 +108,8 @@ public class JsonFieldProcessorTests { List> alpha = Arrays.asList(entry, new HashMap()); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[].b", payload).getValue(), - equalTo((Object) Arrays.asList("bravo"))); + assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()) + .isEqualTo(Arrays.asList("bravo")); } @Test @@ -128,8 +121,8 @@ public class JsonFieldProcessorTests { nullField.put("b", null); List> alpha = Arrays.asList(nonNullField, nullField); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[].b", payload).getValue(), - equalTo((Object) Arrays.asList("bravo", null))); + assertThat(this.fieldProcessor.extract("a[].b", payload).getValue()) + .isEqualTo(Arrays.asList("bravo", null)); } @Test @@ -141,9 +134,8 @@ public class JsonFieldProcessorTests { List>> alpha = Arrays .asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[][]", payload).getValue(), - equalTo((Object) Arrays.asList(Arrays.asList(entry1, entry2), - Arrays.asList(entry3)))); + assertThat(this.fieldProcessor.extract("a[][]", payload).getValue()).isEqualTo( + Arrays.asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3))); } @Test @@ -155,8 +147,8 @@ public class JsonFieldProcessorTests { List>> alpha = Arrays .asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[][].id", payload).getValue(), - equalTo((Object) Arrays.asList("1", "2", "3"))); + assertThat(this.fieldProcessor.extract("a[][].id", payload).getValue()) + .isEqualTo(Arrays.asList("1", "2", "3")); } @Test @@ -168,9 +160,9 @@ public class JsonFieldProcessorTests { List>> alpha = Arrays .asList(Arrays.asList(entry1, entry2), Arrays.asList(entry3)); payload.put("a", alpha); - assertThat(this.fieldProcessor.extract("a[][].ids", payload).getValue(), - equalTo((Object) Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3), - Arrays.asList(4)))); + assertThat(this.fieldProcessor.extract("a[][].ids", payload).getValue()) + .isEqualTo(Arrays.asList(Arrays.asList(1, 2), Arrays.asList(3), + Arrays.asList(4))); } @Test(expected = FieldDoesNotExistException.class) @@ -228,7 +220,7 @@ public class JsonFieldProcessorTests { Map payload = new HashMap<>(); payload.put("a", "alpha"); this.fieldProcessor.remove("a", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @Test @@ -238,7 +230,7 @@ public class JsonFieldProcessorTests { payload.put("a", alpha); alpha.put("b", "bravo"); this.fieldProcessor.remove("a", payload); - assertThat(payload.size(), equalTo(1)); + assertThat(payload.size()).isEqualTo(1); } @Test @@ -248,7 +240,7 @@ public class JsonFieldProcessorTests { payload.put("a", alpha); alpha.put("b", "bravo"); this.fieldProcessor.removeSubsection("a", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @Test @@ -258,7 +250,7 @@ public class JsonFieldProcessorTests { payload.put("a", alpha); alpha.put("b", "bravo"); this.fieldProcessor.remove("a.b", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @SuppressWarnings("unchecked") @@ -267,7 +259,7 @@ public class JsonFieldProcessorTests { Map payload = new ObjectMapper() .readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); this.fieldProcessor.remove("a[].b", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @SuppressWarnings("unchecked") @@ -276,7 +268,7 @@ public class JsonFieldProcessorTests { Map payload = new ObjectMapper() .readValue("{\"a\": [[{\"id\":1},{\"id\":2}], [{\"id\":3}]]}", Map.class); this.fieldProcessor.remove("a[][].id", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @SuppressWarnings("unchecked") @@ -285,7 +277,7 @@ public class JsonFieldProcessorTests { Map payload = new ObjectMapper() .readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); this.fieldProcessor.remove("a[]", payload); - assertThat(payload.size(), equalTo(1)); + assertThat(payload.size()).isEqualTo(1); } @SuppressWarnings("unchecked") @@ -294,7 +286,7 @@ public class JsonFieldProcessorTests { Map payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", Map.class); this.fieldProcessor.remove("a[]", payload); - assertThat(payload.size(), equalTo(1)); + assertThat(payload.size()).isEqualTo(1); } @SuppressWarnings("unchecked") @@ -303,7 +295,7 @@ public class JsonFieldProcessorTests { Map payload = new ObjectMapper() .readValue("{\"a\": [\"bravo\", \"charlie\"]}", Map.class); this.fieldProcessor.remove("a", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @SuppressWarnings("unchecked") @@ -312,7 +304,7 @@ public class JsonFieldProcessorTests { Map payload = new ObjectMapper() .readValue("{\"a\": [{\"b\":\"bravo\"},{\"b\":\"bravo\"}]}", Map.class); this.fieldProcessor.removeSubsection("a[]", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @SuppressWarnings("unchecked") @@ -321,7 +313,7 @@ public class JsonFieldProcessorTests { Map payload = new ObjectMapper().readValue("{\"a\": [[2],[3]]}", Map.class); this.fieldProcessor.removeSubsection("a[]", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @Test @@ -330,8 +322,8 @@ public class JsonFieldProcessorTests { Map alpha = new HashMap<>(); payload.put("a.key", alpha); alpha.put("b.key", "bravo"); - assertThat(this.fieldProcessor.extract("['a.key']['b.key']", payload).getValue(), - equalTo((Object) "bravo")); + assertThat(this.fieldProcessor.extract("['a.key']['b.key']", payload).getValue()) + .isEqualTo("bravo"); } @SuppressWarnings("unchecked") @@ -344,8 +336,8 @@ public class JsonFieldProcessorTests { Map charlie = new LinkedHashMap<>(); charlie.put("b", "bravo2"); payload.put("c", charlie); - assertThat((List) this.fieldProcessor.extract("*.b", payload).getValue(), - contains("bravo1", "bravo2")); + assertThat((List) this.fieldProcessor.extract("*.b", payload).getValue()) + .containsExactly("bravo1", "bravo2"); } @SuppressWarnings("unchecked") @@ -359,8 +351,8 @@ public class JsonFieldProcessorTests { alpha.put("one", bravo); alpha.put("two", bravo); assertThat( - (List) this.fieldProcessor.extract("a.*.b", payload).getValue(), - contains("bravo", "bravo")); + (List) this.fieldProcessor.extract("a.*.b", payload).getValue()) + .containsExactly("bravo", "bravo"); } @SuppressWarnings("unchecked") @@ -373,8 +365,8 @@ public class JsonFieldProcessorTests { Map charlie = new HashMap<>(); charlie.put("b", "bravo2"); payload.put("c", charlie); - assertThat((List) this.fieldProcessor.extract("a.*", payload).getValue(), - contains("bravo1")); + assertThat((List) this.fieldProcessor.extract("a.*", payload).getValue()) + .containsExactly("bravo1"); } @SuppressWarnings("unchecked") @@ -385,8 +377,8 @@ public class JsonFieldProcessorTests { payload.put("a", alpha); alpha.put("b", "bravo1"); alpha.put("c", "charlie"); - assertThat((List) this.fieldProcessor.extract("a.*", payload).getValue(), - contains("bravo1", "charlie")); + assertThat((List) this.fieldProcessor.extract("a.*", payload).getValue()) + .containsExactly("bravo1", "charlie"); } @Test @@ -397,7 +389,7 @@ public class JsonFieldProcessorTests { alpha.put("b", "bravo1"); alpha.put("c", "charlie"); this.fieldProcessor.remove("a.*", payload); - assertThat(payload.size(), equalTo(0)); + assertThat(payload.size()).isEqualTo(0); } @Test @@ -408,7 +400,7 @@ public class JsonFieldProcessorTests { alpha.put("b", "bravo1"); alpha.put("c", "charlie"); this.fieldProcessor.remove("*.b", payload); - assertThat(alpha, not(hasKey("b"))); + assertThat(alpha).doesNotContainKey("b"); } @Test @@ -424,29 +416,29 @@ public class JsonFieldProcessorTests { bravo2.put("b", "bravo"); alpha.put("two", bravo2); this.fieldProcessor.remove("a.*.b", payload); - assertThat(payload.size(), equalTo(1)); - assertThat(payload, hasEntry("c", (Object) "charlie")); + assertThat(payload.size()).isEqualTo(1); + assertThat(payload).containsEntry("c", "charlie"); } @Test public void hasFieldIsTrueForNonNullFieldInMap() throws Exception { Map payload = new HashMap<>(); payload.put("a", "alpha"); - assertThat(this.fieldProcessor.hasField("a", payload), is(true)); + assertThat(this.fieldProcessor.hasField("a", payload)).isTrue(); } @Test public void hasFieldIsTrueForNullFieldInMap() throws Exception { Map payload = new HashMap<>(); payload.put("a", null); - assertThat(this.fieldProcessor.hasField("a", payload), is(true)); + assertThat(this.fieldProcessor.hasField("a", payload)).isTrue(); } @Test public void hasFieldIsFalseForAbsentFieldInMap() throws Exception { Map payload = new HashMap<>(); payload.put("a", null); - assertThat(this.fieldProcessor.hasField("b", payload), is(false)); + assertThat(this.fieldProcessor.hasField("b", payload)).isFalse(); } @Test @@ -455,7 +447,7 @@ public class JsonFieldProcessorTests { Map nested = new HashMap<>(); nested.put("b", "bravo"); payload.put("a", Arrays.asList(nested, nested, nested)); - assertThat(this.fieldProcessor.hasField("a.[].b", payload), is(true)); + assertThat(this.fieldProcessor.hasField("a.[].b", payload)).isTrue(); } @Test @@ -464,7 +456,7 @@ public class JsonFieldProcessorTests { Map nested = new HashMap<>(); nested.put("b", null); payload.put("a", Arrays.asList(nested, nested, nested)); - assertThat(this.fieldProcessor.hasField("a.[].b", payload), is(true)); + assertThat(this.fieldProcessor.hasField("a.[].b", payload)).isTrue(); } @Test @@ -473,7 +465,7 @@ public class JsonFieldProcessorTests { Map nested = new HashMap<>(); nested.put("b", "bravo"); payload.put("a", Arrays.asList(nested, nested, nested)); - assertThat(this.fieldProcessor.hasField("a.[].c", payload), is(false)); + assertThat(this.fieldProcessor.hasField("a.[].c", payload)).isFalse(); } @Test @@ -482,7 +474,7 @@ public class JsonFieldProcessorTests { Map nested = new HashMap<>(); nested.put("b", "bravo"); payload.put("a", Arrays.asList(nested, new HashMap<>(), nested)); - assertThat(this.fieldProcessor.hasField("a.[].b", payload), is(false)); + assertThat(this.fieldProcessor.hasField("a.[].b", payload)).isFalse(); } @Test @@ -493,7 +485,7 @@ public class JsonFieldProcessorTests { Map fieldNull = new HashMap<>(); fieldNull.put("b", null); payload.put("a", Arrays.asList(fieldPresent, fieldPresent, fieldNull)); - assertThat(this.fieldProcessor.hasField("a.[].b", payload), is(false)); + assertThat(this.fieldProcessor.hasField("a.[].b", payload)).isFalse(); } private Map createEntry(String... pairs) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypeResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypeResolverTests.java index a95359ae..3ebb74cf 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypeResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/JsonFieldTypeResolverTests.java @@ -25,8 +25,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JsonFieldTypeResolver}. @@ -47,34 +46,31 @@ public class JsonFieldTypeResolverTests { @Test public void topLevelArray() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("[]"), - new ObjectMapper().readValue("[{\"a\":\"alpha\"}]", List.class)), - equalTo(JsonFieldType.ARRAY)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("[]"), + new ObjectMapper().readValue("[{\"a\":\"alpha\"}]", List.class))) + .isEqualTo(JsonFieldType.ARRAY); } @Test public void nestedArray() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[]"), - createPayload("{\"a\": [{\"b\":\"bravo\"}]}")), - equalTo(JsonFieldType.ARRAY)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[]"), + createPayload("{\"a\": [{\"b\":\"bravo\"}]}"))) + .isEqualTo(JsonFieldType.ARRAY); } @Test public void arrayNestedBeneathAnArray() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].b[]"), - createPayload("{\"a\": [{\"b\": [ 1, 2 ]}]}")), - equalTo(JsonFieldType.ARRAY)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].b[]"), + createPayload("{\"a\": [{\"b\": [ 1, 2 ]}]}"))) + .isEqualTo(JsonFieldType.ARRAY); } @Test public void specificFieldOfObjectInArrayNestedBeneathAnArray() throws IOException { assertThat( this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].b[].c"), - createPayload("{\"a\": [{\"b\": [ {\"c\": 5}, {\"c\": 5}]}]}")), - equalTo(JsonFieldType.NUMBER)); + createPayload("{\"a\": [{\"b\": [ {\"c\": 5}, {\"c\": 5}]}]}"))) + .isEqualTo(JsonFieldType.NUMBER); } @Test @@ -104,115 +100,101 @@ public class JsonFieldTypeResolverTests { @Test public void nestedField() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.b.c"), - createPayload("{\"a\":{\"b\":{\"c\":{}}}}")), - equalTo(JsonFieldType.OBJECT)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.b.c"), + createPayload("{\"a\":{\"b\":{\"c\":{}}}}"))) + .isEqualTo(JsonFieldType.OBJECT); } @Test public void multipleFieldsWithSameType() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload("{\"a\":[{\"id\":1},{\"id\":2}]}")), - equalTo(JsonFieldType.NUMBER)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{\"id\":1},{\"id\":2}]}"))) + .isEqualTo(JsonFieldType.NUMBER); } @Test public void multipleFieldsWithDifferentTypes() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload("{\"a\":[{\"id\":1},{\"id\":true}]}")), - equalTo(JsonFieldType.VARIES)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{\"id\":1},{\"id\":true}]}"))) + .isEqualTo(JsonFieldType.VARIES); } @Test public void multipleFieldsWithDifferentTypesAndSometimesAbsent() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload("{\"a\":[{\"id\":1},{\"id\":true}, { }]}")), - equalTo(JsonFieldType.VARIES)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{\"id\":1},{\"id\":true}, { }]}"))) + .isEqualTo(JsonFieldType.VARIES); } @Test public void multipleFieldsWithDifferentTypesAndSometimesAbsentWhenOptionalResolvesToVaries() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType( - new FieldDescriptor("a[].id").optional(), - createPayload("{\"a\":[{\"id\":1},{\"id\":true}, { }]}")), - equalTo(JsonFieldType.VARIES)); + assertThat(this.fieldTypeResolver.resolveFieldType( + new FieldDescriptor("a[].id").optional(), + createPayload("{\"a\":[{\"id\":1},{\"id\":true}, { }]}"))) + .isEqualTo(JsonFieldType.VARIES); } @Test public void multipleFieldsWhenSometimesAbsent() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload("{\"a\":[{\"id\":1},{ }]}")), - equalTo(JsonFieldType.NUMBER)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{\"id\":1},{ }]}"))) + .isEqualTo(JsonFieldType.NUMBER); } @Test public void multipleFieldsWithDifferentTypesAndSometimesNull() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload( - "{\"a\":[{\"id\":1},{\"id\":true}, {\"id\":null}]}")), - equalTo(JsonFieldType.VARIES)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{\"id\":1},{\"id\":true}, {\"id\":null}]}"))) + .isEqualTo(JsonFieldType.VARIES); } @Test public void multipleFieldsWhenNotNullThenNullWhenRequiredHasVariesType() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload("{\"a\":[{\"id\":1},{\"id\":null}]}")), - equalTo(JsonFieldType.VARIES)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{\"id\":1},{\"id\":null}]}"))) + .isEqualTo(JsonFieldType.VARIES); } @Test public void multipleFieldsWhenNotNullThenNullWhenOptionalHasSpecificType() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType( - new FieldDescriptor("a[].id").optional(), - createPayload("{\"a\":[{\"id\":1},{\"id\":null}]}")), - equalTo(JsonFieldType.NUMBER)); + assertThat(this.fieldTypeResolver.resolveFieldType( + new FieldDescriptor("a[].id").optional(), + createPayload("{\"a\":[{\"id\":1},{\"id\":null}]}"))) + .isEqualTo(JsonFieldType.NUMBER); } @Test public void multipleFieldsWhenNullThenNotNullWhenRequiredHasVariesType() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload("{\"a\":[{\"id\":null},{\"id\":1}]}")), - equalTo(JsonFieldType.VARIES)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{\"id\":null},{\"id\":1}]}"))) + .isEqualTo(JsonFieldType.VARIES); } @Test public void multipleFieldsWhenNullThenNotNullWhenOptionalHasSpecificType() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType( - new FieldDescriptor("a[].id").optional(), - createPayload("{\"a\":[{\"id\":null},{\"id\":1}]}")), - equalTo(JsonFieldType.NUMBER)); + assertThat(this.fieldTypeResolver.resolveFieldType( + new FieldDescriptor("a[].id").optional(), + createPayload("{\"a\":[{\"id\":null},{\"id\":1}]}"))) + .isEqualTo(JsonFieldType.NUMBER); } @Test public void multipleFieldsWhenEitherNullOrAbsent() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload("{\"a\":[{},{\"id\":null}]}")), - equalTo(JsonFieldType.NULL)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{},{\"id\":null}]}"))) + .isEqualTo(JsonFieldType.NULL); } @Test public void multipleFieldsThatAreAllNull() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), - createPayload("{\"a\":[{\"id\":null},{\"id\":null}]}")), - equalTo(JsonFieldType.NULL)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a[].id"), + createPayload("{\"a\":[{\"id\":null},{\"id\":null}]}"))) + .isEqualTo(JsonFieldType.NULL); } @Test @@ -237,40 +219,36 @@ public class JsonFieldTypeResolverTests { @Test public void leafWildcardWithCommonType() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.*"), - createPayload("{\"a\": {\"b\": 5, \"c\": 6}}")), - equalTo(JsonFieldType.NUMBER)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.*"), + createPayload("{\"a\": {\"b\": 5, \"c\": 6}}"))) + .isEqualTo(JsonFieldType.NUMBER); } @Test public void leafWildcardWithVaryingType() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.*"), - createPayload("{\"a\": {\"b\": 5, \"c\": \"six\"}}")), - equalTo(JsonFieldType.VARIES)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.*"), + createPayload("{\"a\": {\"b\": 5, \"c\": \"six\"}}"))) + .isEqualTo(JsonFieldType.VARIES); } @Test public void intermediateWildcardWithCommonType() throws IOException { - assertThat( - this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.*.d"), - createPayload( - "{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": 5}}}}")), - equalTo(JsonFieldType.NUMBER)); + assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.*.d"), + createPayload("{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": 5}}}}"))) + .isEqualTo(JsonFieldType.NUMBER); } @Test public void intermediateWildcardWithVaryingType() throws IOException { assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("a.*.d"), - createPayload("{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": \"four\"}}}}")), - equalTo(JsonFieldType.VARIES)); + createPayload("{\"a\": {\"b\": {\"d\": 4}, \"c\": {\"d\": \"four\"}}}}"))) + .isEqualTo(JsonFieldType.VARIES); } private void assertFieldType(JsonFieldType expectedType, String jsonValue) throws IOException { assertThat(this.fieldTypeResolver.resolveFieldType(new FieldDescriptor("field"), - createSimplePayload(jsonValue)), equalTo(expectedType)); + createSimplePayload(jsonValue))).isEqualTo(expectedType); } private Map createSimplePayload(String value) throws IOException { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java index e17671aa..328bfced 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/PayloadDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,9 +21,7 @@ import java.util.List; import org.junit.Test; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.restdocs.payload.PayloadDocumentation.applyPathPrefix; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.snippet.Attributes.key; @@ -39,42 +37,40 @@ public class PayloadDocumentationTests { public void applyPathPrefixAppliesPrefixToDescriptorPaths() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo"), fieldWithPath("charlie"))); - assertThat(descriptors.size(), is(equalTo(2))); - assertThat(descriptors.get(0).getPath(), is(equalTo("alpha.bravo"))); + assertThat(descriptors.size()).isEqualTo(2); + assertThat(descriptors.get(0).getPath()).isEqualTo("alpha.bravo"); } @Test public void applyPathPrefixCopiesIgnored() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").ignored())); - assertThat(descriptors.size(), is(equalTo(1))); - assertThat(descriptors.get(0).isIgnored(), is(true)); + assertThat(descriptors.size()).isEqualTo(1); + assertThat(descriptors.get(0).isIgnored()).isTrue(); } @Test public void applyPathPrefixCopiesOptional() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").optional())); - assertThat(descriptors.size(), is(equalTo(1))); - assertThat(descriptors.get(0).isOptional(), is(true)); + assertThat(descriptors.size()).isEqualTo(1); + assertThat(descriptors.get(0).isOptional()).isTrue(); } @Test public void applyPathPrefixCopiesDescription() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").description("Some field"))); - assertThat(descriptors.size(), is(equalTo(1))); - assertThat(descriptors.get(0).getDescription(), - is(equalTo((Object) "Some field"))); + assertThat(descriptors.size()).isEqualTo(1); + assertThat(descriptors.get(0).getDescription()).isEqualTo("Some field"); } @Test public void applyPathPrefixCopiesType() { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").type(JsonFieldType.OBJECT))); - assertThat(descriptors.size(), is(equalTo(1))); - assertThat(descriptors.get(0).getType(), - is(equalTo((Object) JsonFieldType.OBJECT))); + assertThat(descriptors.size()).isEqualTo(1); + assertThat(descriptors.get(0).getType()).isEqualTo(JsonFieldType.OBJECT); } @Test @@ -82,12 +78,10 @@ public class PayloadDocumentationTests { List descriptors = applyPathPrefix("alpha.", Arrays.asList(fieldWithPath("bravo").attributes(key("a").value("alpha"), key("b").value("bravo")))); - assertThat(descriptors.size(), is(equalTo(1))); - assertThat(descriptors.get(0).getAttributes().size(), is(equalTo(2))); - assertThat(descriptors.get(0).getAttributes().get("a"), - is(equalTo((Object) "alpha"))); - assertThat(descriptors.get(0).getAttributes().get("b"), - is(equalTo((Object) "bravo"))); + assertThat(descriptors.size()).isEqualTo(1); + assertThat(descriptors.get(0).getAttributes().size()).isEqualTo(2); + assertThat(descriptors.get(0).getAttributes().get("a")).isEqualTo("alpha"); + assertThat(descriptors.get(0).getAttributes().get("b")).isEqualTo("bravo"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java index 5ea5cd74..5febe3ab 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodyPartSnippetTests.java @@ -26,6 +26,7 @@ import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; @@ -46,35 +47,31 @@ public class RequestBodyPartSnippetTests extends AbstractSnippetTests { @Test public void requestPartWithBody() throws IOException { - this.snippets.expect("request-part-one-body") - .withContents(codeBlock(null, "nowrap").content("some content")); - requestPartBody("one").document(this.operationBuilder.request("http://localhost") .part("one", "some content".getBytes()).build()); + assertThat(this.generatedSnippets.snippet("request-part-one-body")) + .is(codeBlock(null, "nowrap").withContent("some content")); } @Test public void requestPartWithNoBody() throws IOException { - this.snippets.expect("request-part-one-body") - .withContents(codeBlock(null, "nowrap").content("")); requestPartBody("one").document(this.operationBuilder.request("http://localhost") .part("one", new byte[0]).build()); + assertThat(this.generatedSnippets.snippet("request-part-one-body")) + .is(codeBlock(null, "nowrap").withContent("")); } @Test public void subsectionOfRequestPartBody() throws IOException { - this.snippets.expect("request-part-one-body-beneath-a.b") - .withContents(codeBlock(null, "nowrap").content("{\"c\":5}")); - requestPartBody("one", beneathPath("a.b")) .document(this.operationBuilder.request("http://localhost") .part("one", "{\"a\":{\"b\":{\"c\":5}}}".getBytes()).build()); + assertThat(this.generatedSnippets.snippet("request-part-one-body-beneath-a.b")) + .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); } @Test public void customSnippetAttributes() throws IOException { - this.snippets.expect("request-part-one-body") - .withContents(codeBlock("json", "nowrap").content("{\"a\":\"alpha\"}")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-part-body")) .willReturn(snippetResource("request-part-body-with-language")); @@ -84,6 +81,8 @@ public class RequestBodyPartSnippetTests extends AbstractSnippetTests { new MustacheTemplateEngine(resolver)) .request("http://localhost") .part("one", "{\"a\":\"alpha\"}".getBytes()).build()); + assertThat(this.generatedSnippets.snippet("request-part-one-body")) + .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java index b9f66335..fbe4bfd8 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestBodySnippetTests.java @@ -26,6 +26,7 @@ import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; @@ -46,34 +47,30 @@ public class RequestBodySnippetTests extends AbstractSnippetTests { @Test public void requestWithBody() throws IOException { - this.snippets.expect("request-body") - .withContents(codeBlock(null, "nowrap").content("some content")); - requestBody().document(this.operationBuilder.request("http://localhost") .content("some content").build()); + assertThat(this.generatedSnippets.snippet("request-body")) + .is(codeBlock(null, "nowrap").withContent("some content")); } @Test public void requestWithNoBody() throws IOException { - this.snippets.expect("request-body") - .withContents(codeBlock(null, "nowrap").content("")); requestBody().document(this.operationBuilder.request("http://localhost").build()); + assertThat(this.generatedSnippets.snippet("request-body")) + .is(codeBlock(null, "nowrap").withContent("")); } @Test public void subsectionOfRequestBody() throws IOException { - this.snippets.expect("request-body-beneath-a.b") - .withContents(codeBlock(null, "nowrap").content("{\"c\":5}")); - requestBody(beneathPath("a.b")) .document(this.operationBuilder.request("http://localhost") .content("{\"a\":{\"b\":{\"c\":5}}}").build()); + assertThat(this.generatedSnippets.snippet("request-body-beneath-a.b")) + .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); } @Test public void customSnippetAttributes() throws IOException { - this.snippets.expect("request-body") - .withContents(codeBlock("json", "nowrap").content("{\"a\":\"alpha\"}")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-body")) .willReturn(snippetResource("request-body-with-language")); @@ -83,6 +80,8 @@ public class RequestBodySnippetTests extends AbstractSnippetTests { new MustacheTemplateEngine(resolver)) .request("http://localhost").content("{\"a\":\"alpha\"}") .build()); + assertThat(this.generatedSnippets.snippet("request-body")) + .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java index ee90a322..feb7b29d 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetFailureTests.java @@ -28,7 +28,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.snippet.SnippetException; import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.test.ExpectedSnippets; import org.springframework.restdocs.test.OperationBuilder; import static org.hamcrest.CoreMatchers.endsWith; @@ -44,10 +43,6 @@ import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWit */ public class RequestFieldsSnippetFailureTests { - @Rule - public ExpectedSnippets snippets = new ExpectedSnippets( - TemplateFormats.asciidoctor()); - @Rule public OperationBuilder operationBuilder = new OperationBuilder( TemplateFormats.asciidoctor()); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java index 7ceb2ab6..22221590 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestFieldsSnippetTests.java @@ -30,10 +30,7 @@ import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; @@ -56,76 +53,65 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { @Test public void mapRequestWithFields() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two") - .row("`a`", "`Object`", "three")); - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"), fieldWithPath("a").description("three"))) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } @Test public void mapRequestWithNullField() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`", - "`Null`", "one")); - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": null}}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", + "one")); } @Test public void entireSubsectionsCanBeDocumented() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a`", - "`Object`", "one")); - new RequestFieldsSnippet( Arrays.asList(subsectionWithPath("a").description("one"))) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Object`", + "one")); } @Test public void subsectionOfMapRequest() throws IOException { - this.snippets.expect("request-fields-beneath-a") - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`b`", "`Number`", "one").row("`c`", "`String`", "two")); - requestFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); + assertThat(this.generatedSnippets.snippet("request-fields-beneath-a")) + .is(tableWithHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "one").row("`c`", "`String`", "two")); } @Test public void subsectionOfMapRequestWithCommonPrefix() throws IOException { - this.snippets.expect("request-fields-beneath-a") - .withContents(tableWithHeader("Path", "Type", "Description").row("`b.c`", - "`String`", "two")); - requestFields(beneathPath("a")) .andWithPrefix("b.", fieldWithPath("c").description("two")) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build()); + assertThat(this.generatedSnippets.snippet("request-fields-beneath-a")) + .is(tableWithHeader("Path", "Type", "Description").row("`b.c`", + "`String`", "two")); } @Test public void arrayRequestWithFields() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`[]`", "`Array`", "one").row("`[]a.b`", "`Number`", "two") - .row("`[]a.c`", "`String`", "three") - .row("`[]a`", "`Object`", "four")); - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one"), fieldWithPath("[]a.b").description("two"), fieldWithPath("[]a.c").description("three"), @@ -134,113 +120,113 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { .content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]") .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`[]`", "`Array`", "one").row("`[]a.b`", "`Number`", "two") + .row("`[]a.c`", "`String`", "three") + .row("`[]a`", "`Object`", "four")); } @Test public void arrayRequestWithAlwaysNullField() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`[]a.b`", "`Null`", "one")); - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"))) .document(this.operationBuilder.request("http://localhost") .content("[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]") .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", + "`Null`", "one")); } @Test public void subsectionOfArrayRequest() throws IOException { - this.snippets.expect("request-fields-beneath-[].a") - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`b`", "`Number`", "one").row("`c`", "`String`", "two")); - requestFields(beneathPath("[].a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) .document(this.operationBuilder.request("http://localhost") .content("[{\"a\": {\"b\": 5, \"c\": \"charlie\"}}]") .build()); + assertThat(this.generatedSnippets.snippet("request-fields-beneath-[].a")) + .is(tableWithHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "one").row("`c`", "`String`", "two")); } @Test public void ignoredRequestField() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`b`", - "`Number`", "Field b")); - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b"))) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": 5, \"b\": 4}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", + "Field b")); } @Test public void entireSubsectionCanBeIgnored() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`c`", - "`Number`", "Field c")); - new RequestFieldsSnippet(Arrays.asList(subsectionWithPath("a").ignored(), fieldWithPath("c").description("Field c"))) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5}, \"c\": 4}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`c`", "`Number`", + "Field c")); } @Test public void allUndocumentedRequestFieldsCanBeIgnored() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`b`", - "`Number`", "Field b")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true).document( this.operationBuilder.request("http://localhost") .content("{\"a\": 5, \"b\": 4}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", + "Field b")); } @Test public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`b`", "`Number`", "Field b") - .row("`c.d`", "`Number`", "Field d")); - new RequestFieldsSnippet(Arrays.asList(fieldWithPath("b").description("Field b")), true).andWithPrefix("c.", fieldWithPath("d").description("Field d")) .document(this.operationBuilder.request("http://localhost") .content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "Field b") + .row("`c.d`", "`Number`", "Field d")); } @Test public void missingOptionalRequestField() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`", - "`String`", "one")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one") .type(JsonFieldType.STRING).optional())) .document(this.operationBuilder.request("http://localhost") .content("{}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", + "`String`", "one")); } @Test public void missingIgnoredOptionalRequestFieldDoesNotRequireAType() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description")); new RequestFieldsSnippet(Arrays .asList(fieldWithPath("a.b").description("one").ignored().optional())) .document(this.operationBuilder.request("http://localhost") .content("{}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description")); } @Test public void presentOptionalRequestField() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`", - "`String`", "one")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one") .type(JsonFieldType.STRING).optional())) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": { \"b\": \"bravo\"}}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", + "`String`", "one")); } @Test @@ -248,8 +234,6 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) .willReturn(snippetResource("request-fields-with-title")); - this.snippets.expectRequestFields().withContents(containsString("Custom title")); - new RequestFieldsSnippet( Arrays.asList(fieldWithPath("a").description("one")), attributes( key("title").value("Custom title"))) @@ -260,6 +244,7 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { resolver)) .request("http://localhost") .content("{\"a\": \"foo\"}").build()); + assertThat(this.generatedSnippets.requestFields()).contains("Custom title"); } @Test @@ -267,12 +252,6 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-fields")) .willReturn(snippetResource("request-fields-with-extra-column")); - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description", "Foo") - .row("a.b", "Number", "one", "alpha") - .row("a.c", "String", "two", "bravo") - .row("a", "Object", "three", "charlie")); - new RequestFieldsSnippet(Arrays.asList( fieldWithPath("a.b").description("one") .attributes(key("foo").value("alpha")), @@ -287,30 +266,33 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { .content( "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description", "Foo") + .row("a.b", "Number", "one", "alpha") + .row("a.c", "String", "two", "bravo") + .row("a", "Object", "three", "charlie")); } @Test public void fieldWithExplictExactlyMatchingType() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a`", - "`Number`", "one")); - new RequestFieldsSnippet(Arrays .asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER))) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": 5 }").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", + "one")); } @Test public void fieldWithExplictVariesType() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a`", - "`Varies`", "one")); - new RequestFieldsSnippet(Arrays .asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES))) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": 5 }").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", + "one")); } @Test @@ -329,11 +311,6 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { } private void xmlRequestFields(MediaType contentType) throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a/b`", "`b`", "one").row("`a/c`", "`c`", "two") - .row("`a`", "`a`", "three")); - new RequestFieldsSnippet(Arrays.asList( fieldWithPath("a/b").description("one").type("b"), fieldWithPath("a/c").description("two").type("c"), @@ -342,13 +319,13 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { .content("5charlie") .header(HttpHeaders.CONTENT_TYPE, contentType.toString()) .build()); + assertThat(this.generatedSnippets.requestFields()).is( + tableWithHeader("Path", "Type", "Description").row("`a/b`", "`b`", "one") + .row("`a/c`", "`c`", "two").row("`a`", "`a`", "three")); } @Test public void entireSubsectionOfXmlPayloadCanBeDocumented() throws IOException { - this.snippets.expectRequestFields().withContents( - tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); - new RequestFieldsSnippet( Arrays.asList(subsectionWithPath("a").description("one").type("a"))) .document(this.operationBuilder.request("http://localhost") @@ -356,57 +333,51 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) .build()); + assertThat(this.generatedSnippets.requestFields()).is( + tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two") - .row("`a`", "`Object`", "three")); - PayloadDocumentation .requestFields(fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two")) .and(fieldWithPath("a").description("three")) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } @Test public void prefixedAdditionalDescriptors() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two") - .row("`a.c`", "`String`", "three")); - PayloadDocumentation.requestFields(fieldWithPath("a").description("one")) .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) .document(this.operationBuilder.request("http://localhost") .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); } @Test public void requestWithFieldsWithEscapedContent() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row( - escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), - escapeIfNecessary("three|four"))); - new RequestFieldsSnippet(Arrays.asList( fieldWithPath("Foo|Bar").type("one|two").description("three|four"))) .document(this.operationBuilder.request("http://localhost") .content("{\"Foo|Bar\": 5}").build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row( + escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), + escapeIfNecessary("three|four"))); } @Test public void mapRequestWithVaryingKeysMatchedUsingWildcard() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`things.*.size`", "`String`", "one") - .row("`things.*.type`", "`String`", "two")); - new RequestFieldsSnippet( Arrays.asList(fieldWithPath("things.*.size").description("one"), fieldWithPath("things.*.type").description("two"))).document( @@ -416,13 +387,14 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { + "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}") .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`things.*.size`", "`String`", "one") + .row("`things.*.type`", "`String`", "two")); } @Test public void requestWithArrayContainingFieldThatIsSometimesNull() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`assets[].name`", "`String`", "one")); new RequestFieldsSnippet(Arrays.asList(fieldWithPath("assets[].name") .description("one").type(JsonFieldType.STRING).optional())) .document(this.operationBuilder.request("http://localhost") @@ -430,14 +402,13 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { + "{\"name\": null}, " + "{\"name\": \"sample2\"}]}") .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", + "`String`", "one")); } @Test public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a[].b`", "`Number`", "one") - .row("`a[].c`", "`Number`", "two")); new RequestFieldsSnippet(Arrays.asList( fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER) .optional(), @@ -447,17 +418,21 @@ public class RequestFieldsSnippetTests extends AbstractSnippetTests { .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") .build()); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a[].b`", "`Number`", "one") + .row("`a[].c`", "`Number`", "two")); } @Test public void typeDeterminationDoesNotSetTypeOnDescriptor() throws IOException { - this.snippets.expectRequestFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`", - "`Number`", "one")); FieldDescriptor descriptor = fieldWithPath("a.b").description("one"); new RequestFieldsSnippet(Arrays.asList(descriptor)).document(this.operationBuilder .request("http://localhost").content("{\"a\": {\"b\": 5}}").build()); - assertThat(descriptor.getType(), is(nullValue())); + assertThat(descriptor.getType()).isNull(); + assertThat(this.generatedSnippets.requestFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", + "`Number`", "one")); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java index f03b5cc1..6942240f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/RequestPartFieldsSnippetTests.java @@ -26,6 +26,7 @@ import org.springframework.restdocs.AbstractSnippetTests; import org.springframework.restdocs.operation.Operation; import org.springframework.restdocs.templates.TemplateFormat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; @@ -43,11 +44,6 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { @Test public void mapRequestPartFields() throws IOException { - this.snippets.expectRequestPartFields("one") - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two") - .row("`a`", "`Object`", "three")); - new RequestPartFieldsSnippet("one", Arrays.asList( fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two"), @@ -55,52 +51,50 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { .request("http://localhost") .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) .build()); + assertThat(this.generatedSnippets.requestPartFields("one")) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } @Test public void mapRequestPartSubsectionFields() throws IOException { - this.snippets.expect("request-part-one-fields-beneath-a") - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`b`", "`Number`", "one").row("`c`", "`String`", "two")); - new RequestPartFieldsSnippet("one", beneathPath("a"), Arrays.asList( fieldWithPath("b").description("one"), fieldWithPath("c").description("two"))).document(this.operationBuilder .request("http://localhost") .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) .build()); + assertThat(this.generatedSnippets.snippet("request-part-one-fields-beneath-a")) + .is(tableWithHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "one").row("`c`", "`String`", "two")); } @Test public void multipleRequestParts() throws IOException { - this.snippets.expectRequestPartFields("one"); - this.snippets.expectRequestPartFields("two"); Operation operation = this.operationBuilder.request("http://localhost") .part("one", "{}".getBytes()).and().part("two", "{}".getBytes()).build(); new RequestPartFieldsSnippet("one", Collections.emptyList()) .document(operation); new RequestPartFieldsSnippet("two", Collections.emptyList()) .document(operation); + assertThat(this.generatedSnippets.requestPartFields("one")).isNotNull(); + assertThat(this.generatedSnippets.requestPartFields("two")).isNotNull(); } @Test public void allUndocumentedRequestPartFieldsCanBeIgnored() throws IOException { - this.snippets.expectRequestPartFields("one") - .withContents(tableWithHeader("Path", "Type", "Description").row("`b`", - "`Number`", "Field b")); new RequestPartFieldsSnippet("one", Arrays.asList(fieldWithPath("b").description("Field b")), true) .document(this.operationBuilder.request("http://localhost") .part("one", "{\"a\": 5, \"b\": 4}".getBytes()).build()); + assertThat(this.generatedSnippets.requestPartFields("one")) + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", + "Field b")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectRequestPartFields("one") - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two") - .row("`a`", "`Object`", "three")); - PayloadDocumentation .requestPartFields("one", fieldWithPath("a.b").description("one"), fieldWithPath("a.c").description("two")) @@ -108,15 +102,14 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { .document(this.operationBuilder.request("http://localhost") .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) .build()); + assertThat(this.generatedSnippets.requestPartFields("one")) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a.b`", "`Number`", "one").row("`a.c`", "`String`", "two") + .row("`a`", "`Object`", "three")); } @Test public void prefixedAdditionalDescriptors() throws IOException { - this.snippets.expectRequestPartFields("one") - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two") - .row("`a.c`", "`String`", "three")); - PayloadDocumentation .requestPartFields("one", fieldWithPath("a").description("one")) .andWithPrefix("a.", fieldWithPath("b").description("two"), @@ -124,6 +117,10 @@ public class RequestPartFieldsSnippetTests extends AbstractSnippetTests { .document(this.operationBuilder.request("http://localhost") .part("one", "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}".getBytes()) .build()); + assertThat(this.generatedSnippets.requestPartFields("one")) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java index d01bc396..a8667caa 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseBodySnippetTests.java @@ -26,6 +26,7 @@ import org.springframework.restdocs.templates.TemplateFormat; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; @@ -46,42 +47,39 @@ public class ResponseBodySnippetTests extends AbstractSnippetTests { @Test public void responseWithBody() throws IOException { - this.snippets.expect("response-body") - .withContents(codeBlock(null, "nowrap").content("some content")); - - PayloadDocumentation.responseBody().document( + new ResponseBodySnippet().document( this.operationBuilder.response().content("some content").build()); + assertThat(this.generatedSnippets.snippet("response-body")) + .is(codeBlock(null, "nowrap").withContent("some content")); } @Test public void responseWithNoBody() throws IOException { - this.snippets.expect("response-body") - .withContents(codeBlock(null, "nowrap").content("")); - PayloadDocumentation.responseBody() - .document(this.operationBuilder.response().build()); + new ResponseBodySnippet().document(this.operationBuilder.response().build()); + assertThat(this.generatedSnippets.snippet("response-body")) + .is(codeBlock(null, "nowrap").withContent("")); } @Test public void subsectionOfResponseBody() throws IOException { - this.snippets.expect("response-body-beneath-a.b") - .withContents(codeBlock(null, "nowrap").content("{\"c\":5}")); - responseBody(beneathPath("a.b")).document(this.operationBuilder.response() .content("{\"a\":{\"b\":{\"c\":5}}}").build()); + assertThat(this.generatedSnippets.snippet("response-body-beneath-a.b")) + .is(codeBlock(null, "nowrap").withContent("{\"c\":5}")); } @Test public void customSnippetAttributes() throws IOException { - this.snippets.expect("response-body") - .withContents(codeBlock("json", "nowrap").content("{\"a\":\"alpha\"}")); TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-body")) .willReturn(snippetResource("response-body-with-language")); - responseBody(attributes(key("language").value("json"))) + new ResponseBodySnippet(attributes(key("language").value("json"))) .document(this.operationBuilder .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) .response().content("{\"a\":\"alpha\"}").build()); + assertThat(this.generatedSnippets.snippet("response-body")) + .is(codeBlock("json", "nowrap").withContent("{\"a\":\"alpha\"}")); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java index 3526a0ab..679cab34 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetFailureTests.java @@ -27,7 +27,6 @@ import org.junit.rules.ExpectedException; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.test.ExpectedSnippets; import org.springframework.restdocs.test.OperationBuilder; import static org.hamcrest.CoreMatchers.endsWith; @@ -47,9 +46,6 @@ public class ResponseFieldsSnippetFailureTests { @Rule public OperationBuilder operationBuilder = new OperationBuilder(asciidoctor()); - @Rule - public ExpectedSnippets snippets = new ExpectedSnippets(asciidoctor()); - @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java index 9388dd1e..d31448d8 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/ResponseFieldsSnippetTests.java @@ -30,10 +30,7 @@ import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.payload.PayloadDocumentation.beneathPath; @@ -55,13 +52,6 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { @Test public void mapResponseWithFields() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`id`", "`Number`", "one").row("`date`", "`String`", "two") - .row("`assets`", "`Array`", "three") - .row("`assets[]`", "`Array`", "four") - .row("`assets[].id`", "`Number`", "five") - .row("`assets[].name`", "`String`", "six")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"), fieldWithPath("assets").description("three"), @@ -73,49 +63,50 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { "{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + " [{\"id\":356,\"name\": \"sample\"}]}") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`id`", "`Number`", "one").row("`date`", "`String`", "two") + .row("`assets`", "`Array`", "three") + .row("`assets[]`", "`Array`", "four") + .row("`assets[].id`", "`Number`", "five") + .row("`assets[].name`", "`String`", "six")); } @Test public void mapResponseWithNullField() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`", - "`Null`", "one")); - new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one"))) .document(this.operationBuilder.response() .content("{\"a\": {\"b\": null}}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", "`Null`", + "one")); } @Test public void subsectionOfMapResponse() throws IOException { - this.snippets.expect("response-fields-beneath-a") - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`b`", "`Number`", "one").row("`c`", "`String`", "two")); responseFields(beneathPath("a"), fieldWithPath("b").description("one"), fieldWithPath("c").description("two")) .document(this.operationBuilder.response() .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); + assertThat(this.generatedSnippets.snippet("response-fields-beneath-a")) + .is(tableWithHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "one").row("`c`", "`String`", "two")); } @Test public void subsectionOfMapResponseWithCommonsPrefix() throws IOException { - this.snippets.expect("response-fields-beneath-a") - .withContents(tableWithHeader("Path", "Type", "Description").row("`b.c`", - "`String`", "two")); responseFields(beneathPath("a")) .andWithPrefix("b.", fieldWithPath("c").description("two")) .document(this.operationBuilder.response() .content("{\"a\": {\"b\": {\"c\": \"charlie\"}}}").build()); + assertThat(this.generatedSnippets.snippet("response-fields-beneath-a")) + .is(tableWithHeader("Path", "Type", "Description").row("`b.c`", + "`String`", "two")); } @Test public void arrayResponseWithFields() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`[]a.b`", "`Number`", "one") - .row("`[]a.c`", "`String`", "two") - .row("`[]a`", "`Object`", "three")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]a.b").description("one"), fieldWithPath("[]a.c").description("two"), fieldWithPath("[]a").description("three"))) @@ -123,68 +114,69 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { .content("[{\"a\": {\"b\": 5, \"c\":\"charlie\"}}," + "{\"a\": {\"b\": 4, \"c\":\"chalk\"}}]") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`[]a.b`", "`Number`", "one") + .row("`[]a.c`", "`String`", "two") + .row("`[]a`", "`Object`", "three")); } @Test public void arrayResponseWithAlwaysNullField() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`[]a.b`", "`Null`", "one")); - new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("[]a.b").description("one"))) .document(this.operationBuilder.response().content( "[{\"a\": {\"b\": null}}," + "{\"a\": {\"b\": null}}]") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`[]a.b`", + "`Null`", "one")); } @Test public void arrayResponse() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`[]`", - "`Array`", "one")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("[]").description("one"))) .document(this.operationBuilder.response() .content("[\"a\", \"b\", \"c\"]").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`[]`", "`Array`", + "one")); } @Test public void ignoredResponseField() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`b`", - "`Number`", "Field b")); - new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a").ignored(), fieldWithPath("b").description("Field b"))) .document(this.operationBuilder.response() .content("{\"a\": 5, \"b\": 4}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", + "Field b")); } @Test public void allUndocumentedFieldsCanBeIgnored() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`b`", - "`Number`", "Field b")); - new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("b").description("Field b")), true) .document(this.operationBuilder.response() .content("{\"a\": 5, \"b\": 4}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`b`", "`Number`", + "Field b")); } @Test public void allUndocumentedFieldsContinueToBeIgnoredAfterAddingDescriptors() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`b`", "`Number`", "Field b") - .row("`c.d`", "`Number`", "Field d")); - new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("b").description("Field b")), true) .andWithPrefix("c.", fieldWithPath("d").description("Field d")) .document(this.operationBuilder.response() .content("{\"a\":5,\"b\":4,\"c\":{\"d\": 3}}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`b`", "`Number`", "Field b") + .row("`c.d`", "`Number`", "Field d")); } @Test @@ -192,8 +184,6 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-fields")) .willReturn(snippetResource("response-fields-with-title")); - this.snippets.expectResponseFields().withContents(containsString("Custom title")); - new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a").description("one")), attributes( key("title").value("Custom title"))) @@ -204,37 +194,38 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { resolver)) .response().content("{\"a\": \"foo\"}") .build()); + assertThat(this.generatedSnippets.responseFields()).contains("Custom title"); } @Test public void missingOptionalResponseField() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`", - "`String`", "one")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one") .type(JsonFieldType.STRING).optional())) .document(this.operationBuilder.response().content("{}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", + "`String`", "one")); } @Test public void missingIgnoredOptionalResponseFieldDoesNotRequireAType() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description")); new ResponseFieldsSnippet(Arrays .asList(fieldWithPath("a.b").description("one").ignored().optional())) .document(this.operationBuilder.response().content("{}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description")); } @Test public void presentOptionalResponseField() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a.b`", - "`String`", "one")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("a.b").description("one") .type(JsonFieldType.STRING).optional())) .document(this.operationBuilder.response() .content("{\"a\": { \"b\": \"bravo\"}}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a.b`", + "`String`", "one")); } @Test @@ -242,12 +233,6 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("response-fields")) .willReturn(snippetResource("response-fields-with-extra-column")); - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description", "Foo") - .row("a.b", "Number", "one", "alpha") - .row("a.c", "String", "two", "bravo") - .row("a", "Object", "three", "charlie")); - new ResponseFieldsSnippet(Arrays.asList( fieldWithPath("a.b").description("one") .attributes(key("foo").value("alpha")), @@ -262,30 +247,33 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { .content( "{\"a\": {\"b\": 5, \"c\": \"charlie\"}}") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description", "Foo") + .row("a.b", "Number", "one", "alpha") + .row("a.c", "String", "two", "bravo") + .row("a", "Object", "three", "charlie")); } @Test public void fieldWithExplictExactlyMatchingType() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a`", - "`Number`", "one")); - new ResponseFieldsSnippet(Arrays .asList(fieldWithPath("a").description("one").type(JsonFieldType.NUMBER))) .document(this.operationBuilder.response().content("{\"a\": 5 }") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Number`", + "one")); } @Test public void fieldWithExplictVariesType() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`a`", - "`Varies`", "one")); - new ResponseFieldsSnippet(Arrays .asList(fieldWithPath("a").description("one").type(JsonFieldType.VARIES))) .document(this.operationBuilder.response().content("{\"a\": 5 }") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`a`", "`Varies`", + "one")); } @Test @@ -304,10 +292,6 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { } private void xmlResponseFields(MediaType contentType) throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a/b`", "`b`", "one").row("`a/c`", "`c`", "two") - .row("`a`", "`a`", "three")); new ResponseFieldsSnippet(Arrays.asList( fieldWithPath("a/b").description("one").type("b"), fieldWithPath("a/c").description("two").type("c"), @@ -316,13 +300,13 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { .content("5charlie") .header(HttpHeaders.CONTENT_TYPE, contentType.toString()) .build()); + assertThat(this.generatedSnippets.responseFields()).is( + tableWithHeader("Path", "Type", "Description").row("`a/b`", "`b`", "one") + .row("`a/c`", "`c`", "two").row("`a`", "`a`", "three")); } @Test public void xmlAttribute() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a").description("one").type("b"), fieldWithPath("a/@id").description("two").type("c"))) @@ -332,13 +316,13 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); } @Test public void missingOptionalXmlAttribute() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a").description("one").type("b"), fieldWithPath("a/@id").description("two").type("c").optional())) @@ -348,29 +332,25 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a`", "`b`", "one").row("`a/@id`", "`c`", "two")); } @Test public void undocumentedAttributeDoesNotCauseFailure() throws IOException { - this.snippets.expectResponseFields().withContents( - tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("a").description("one").type("a"))).document( this.operationBuilder.response().content("bar") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML_VALUE) .build()); + assertThat(this.generatedSnippets.responseFields()).is( + tableWithHeader("Path", "Type", "Description").row("`a`", "`a`", "one")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`id`", "`Number`", "one").row("`date`", "`String`", "two") - .row("`assets`", "`Array`", "three") - .row("`assets[]`", "`Array`", "four") - .row("`assets[].id`", "`Number`", "five") - .row("`assets[].name`", "`String`", "six")); PayloadDocumentation .responseFields(fieldWithPath("id").description("one"), fieldWithPath("date").description("two"), @@ -382,42 +362,42 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { .content("{\"id\": 67,\"date\": \"2015-01-20\",\"assets\":" + " [{\"id\":356,\"name\": \"sample\"}]}") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`id`", "`Number`", "one").row("`date`", "`String`", "two") + .row("`assets`", "`Array`", "three") + .row("`assets[]`", "`Array`", "four") + .row("`assets[].id`", "`Number`", "five") + .row("`assets[].name`", "`String`", "six")); } @Test public void prefixedAdditionalDescriptors() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two") - .row("`a.c`", "`String`", "three")); - PayloadDocumentation.responseFields(fieldWithPath("a").description("one")) .andWithPrefix("a.", fieldWithPath("b").description("two"), fieldWithPath("c").description("three")) .document(this.operationBuilder.response() .content("{\"a\": {\"b\": 5, \"c\": \"charlie\"}}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a`", "`Object`", "one").row("`a.b`", "`Number`", "two") + .row("`a.c`", "`String`", "three")); } @Test public void responseWithFieldsWithEscapedContent() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row( - escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), - escapeIfNecessary("three|four"))); - new ResponseFieldsSnippet(Arrays.asList( fieldWithPath("Foo|Bar").type("one|two").description("three|four"))) .document(this.operationBuilder.response() .content("{\"Foo|Bar\": 5}").build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row( + escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("`one|two`"), + escapeIfNecessary("three|four"))); } @Test public void mapResponseWithVaryingKeysMatchedUsingWildcard() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`things.*.size`", "`String`", "one") - .row("`things.*.type`", "`String`", "two")); - new ResponseFieldsSnippet( Arrays.asList(fieldWithPath("things.*.size").description("one"), fieldWithPath("things.*.type").description("two"))) @@ -427,13 +407,14 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { + "\"gzM33\" : {\"type\": \"Screw\"," + "\"size\": \"SMALL\"}}}") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`things.*.size`", "`String`", "one") + .row("`things.*.type`", "`String`", "two")); } @Test public void responseWithArrayContainingFieldThatIsSometimesNull() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`assets[].name`", "`String`", "one")); new ResponseFieldsSnippet(Arrays.asList(fieldWithPath("assets[].name") .description("one").type(JsonFieldType.STRING).optional())) .document(this.operationBuilder.response() @@ -441,14 +422,13 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { + "{\"name\": null}, " + "{\"name\": \"sample2\"}]}") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`assets[].name`", + "`String`", "one")); } @Test public void optionalFieldBeneathArrayThatIsSometimesAbsent() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description") - .row("`a[].b`", "`Number`", "one") - .row("`a[].c`", "`Number`", "two")); new ResponseFieldsSnippet(Arrays.asList( fieldWithPath("a[].b").description("one").type(JsonFieldType.NUMBER) .optional(), @@ -458,17 +438,21 @@ public class ResponseFieldsSnippetTests extends AbstractSnippetTests { .content("{\"a\":[{\"b\": 1,\"c\": 2}, " + "{\"c\": 2}, {\"b\": 1,\"c\": 2}]}") .build()); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description") + .row("`a[].b`", "`Number`", "one") + .row("`a[].c`", "`Number`", "two")); } @Test public void typeDeterminationDoesNotSetTypeOnDescriptor() throws IOException { - this.snippets.expectResponseFields() - .withContents(tableWithHeader("Path", "Type", "Description").row("`id`", - "`Number`", "one")); FieldDescriptor descriptor = fieldWithPath("id").description("one"); new ResponseFieldsSnippet(Arrays.asList(descriptor)).document( this.operationBuilder.response().content("{\"id\": 67}").build()); - assertThat(descriptor.getType(), is(nullValue())); + assertThat(descriptor.getType()).isNull(); + assertThat(this.generatedSnippets.responseFields()) + .is(tableWithHeader("Path", "Type", "Description").row("`id`", "`Number`", + "one")); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java index 064ed972..904093b8 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/payload/XmlContentHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +22,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath; @@ -43,7 +40,7 @@ public class XmlContentHandlerTests { public void topLevelElementCanBeDocumented() { String undocumentedContent = createHandler("5").getUndocumentedContent( Arrays.asList(fieldWithPath("a").type("a").description("description"))); - assertThat(undocumentedContent, is(nullValue())); + assertThat(undocumentedContent).isNull(); } @Test @@ -51,7 +48,7 @@ public class XmlContentHandlerTests { String undocumentedContent = createHandler("5") .getUndocumentedContent(Arrays.asList( fieldWithPath("a/b").type("b").description("description"))); - assertThat(undocumentedContent, is(equalTo(String.format("%n")))); + assertThat(undocumentedContent).isEqualTo(String.format("%n")); } @Test @@ -59,8 +56,8 @@ public class XmlContentHandlerTests { String undocumentedContent = createHandler("5") .getUndocumentedContent(Arrays .asList(fieldWithPath("a").type("a").description("description"))); - assertThat(undocumentedContent, - is(equalTo(String.format("%n 5%n%n")))); + assertThat(undocumentedContent) + .isEqualTo(String.format("%n 5%n%n")); } @Test @@ -68,7 +65,7 @@ public class XmlContentHandlerTests { String undocumentedContent = createHandler("5") .getUndocumentedContent(Arrays.asList( subsectionWithPath("a").type("a").description("description"))); - assertThat(undocumentedContent, is(nullValue())); + assertThat(undocumentedContent).isNull(); } @Test @@ -77,7 +74,7 @@ public class XmlContentHandlerTests { .getUndocumentedContent(Arrays.asList( fieldWithPath("a").type("a").description("description"), fieldWithPath("a/b").type("b").description("description"))); - assertThat(undocumentedContent, is(nullValue())); + assertThat(undocumentedContent).isNull(); } @Test @@ -86,7 +83,7 @@ public class XmlContentHandlerTests { .getUndocumentedContent(Arrays.asList( fieldWithPath("a/b").type("b").description("description"), fieldWithPath("a").type("a").description("description"))); - assertThat(undocumentedContent, is(nullValue())); + assertThat(undocumentedContent).isNull(); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java index 27a897d5..5941151b 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetFailureTests.java @@ -26,7 +26,6 @@ import org.junit.rules.ExpectedException; import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.test.ExpectedSnippets; import org.springframework.restdocs.test.OperationBuilder; import static org.hamcrest.CoreMatchers.equalTo; @@ -44,9 +43,6 @@ public class PathParametersSnippetFailureTests { @Rule public OperationBuilder operationBuilder = new OperationBuilder(asciidoctor()); - @Rule - public ExpectedSnippets snippets = new ExpectedSnippets(asciidoctor()); - @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java index 47060e89..971ae21f 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/PathParametersSnippetTests.java @@ -29,7 +29,7 @@ import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; @@ -49,86 +49,86 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { @Test public void pathParameters() throws IOException { - this.snippets.expectPathParameters().withContents( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description") - .row("`a`", "one").row("`b`", "two")); new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))).document(this.operationBuilder .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description") + .row("`a`", "one").row("`b`", "two")); } @Test public void ignoredPathParameter() throws IOException { - this.snippets.expectPathParameters().withContents( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", - "two")); new PathParametersSnippet(Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two"))).document(this.operationBuilder .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description") + .row("`b`", "two")); } @Test public void allUndocumentedPathParametersCanBeIgnored() throws IOException { - this.snippets.expectPathParameters().withContents( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description").row("`b`", - "two")); new PathParametersSnippet( Arrays.asList(parameterWithName("b").description("two")), true) .document(this.operationBuilder.attribute( RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}").build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description") + .row("`b`", "two")); } @Test public void missingOptionalPathParameter() throws IOException { - this.snippets.expectPathParameters().withContents( - tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description") - .row("`a`", "one").row("`b`", "two")); new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two").optional())) .document(this.operationBuilder.attribute( RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}").build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description") + .row("`a`", "one").row("`b`", "two")); } @Test public void presentOptionalPathParameter() throws IOException { - this.snippets.expectPathParameters().withContents( - tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description") - .row("`a`", "one")); new PathParametersSnippet( Arrays.asList(parameterWithName("a").description("one").optional())) .document(this.operationBuilder.attribute( RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}").build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle("/{a}"), "Parameter", "Description") + .row("`a`", "one")); } @Test public void pathParametersWithQueryString() throws IOException { - this.snippets.expectPathParameters().withContents( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description") - .row("`a`", "one").row("`b`", "two")); new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))).document(this.operationBuilder .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo=bar") .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description") + .row("`a`", "one").row("`b`", "two")); } @Test public void pathParametersWithQueryStringWithParameters() throws IOException { - this.snippets.expectPathParameters().withContents( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description") - .row("`a`", "one").row("`b`", "two")); new PathParametersSnippet(Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))).document(this.operationBuilder .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}?foo={c}") .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description") + .row("`a`", "one").row("`b`", "two")); } @Test @@ -136,8 +136,6 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("path-parameters")) .willReturn(snippetResource("path-parameters-with-title")); - this.snippets.expectPathParameters().withContents(containsString("The title")); - new PathParametersSnippet( Arrays.asList( parameterWithName("a").description("one") @@ -151,7 +149,7 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) .build()); - + assertThat(this.generatedSnippets.pathParameters()).contains("The title"); } @Test @@ -159,10 +157,6 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("path-parameters")) .willReturn(snippetResource("path-parameters-with-extra-column")); - this.snippets.expectPathParameters() - .withContents(tableWithHeader("Parameter", "Description", "Foo") - .row("a", "one", "alpha").row("b", "two", "bravo")); - new PathParametersSnippet(Arrays.asList( parameterWithName("a").description("one") .attributes(key("foo").value("alpha")), @@ -173,34 +167,36 @@ public class PathParametersSnippetTests extends AbstractSnippetTests { .attribute(TemplateEngine.class.getName(), new MustacheTemplateEngine(resolver)) .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithHeader("Parameter", "Description", "Foo") + .row("a", "one", "alpha").row("b", "two", "bravo")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectPathParameters().withContents( - tableWithTitleAndHeader(getTitle(), "Parameter", "Description") - .row("`a`", "one").row("`b`", "two")); RequestDocumentation.pathParameters(parameterWithName("a").description("one")) .and(parameterWithName("b").description("two")) .document(this.operationBuilder .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "/{a}/{b}") .build()); + assertThat(this.generatedSnippets.pathParameters()) + .is(tableWithTitleAndHeader(getTitle(), "Parameter", "Description") + .row("`a`", "one").row("`b`", "two")); } @Test public void pathParametersWithEscapedContent() throws IOException { - this.snippets.expectPathParameters() - .withContents(tableWithTitleAndHeader(getTitle("{Foo|Bar}"), "Parameter", - "Description").row(escapeIfNecessary("`Foo|Bar`"), - escapeIfNecessary("one|two"))); - RequestDocumentation .pathParameters(parameterWithName("Foo|Bar").description("one|two")) .document(this.operationBuilder .attribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE, "{Foo|Bar}") .build()); + assertThat(this.generatedSnippets.pathParameters()).is( + tableWithTitleAndHeader(getTitle("{Foo|Bar}"), "Parameter", "Description") + .row(escapeIfNecessary("`Foo|Bar`"), + escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java index a979f65e..e1c923ea 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetFailureTests.java @@ -25,7 +25,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.test.ExpectedSnippets; import org.springframework.restdocs.test.OperationBuilder; import static org.hamcrest.CoreMatchers.equalTo; @@ -43,9 +42,6 @@ public class RequestParametersSnippetFailureTests { @Rule public OperationBuilder operationBuilder = new OperationBuilder(asciidoctor()); - @Rule - public ExpectedSnippets snippets = new ExpectedSnippets(asciidoctor()); - @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java index da1fecbe..137eca62 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestParametersSnippetTests.java @@ -28,7 +28,7 @@ import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; @@ -48,66 +48,66 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { @Test public void requestParameters() throws IOException { - this.snippets.expectRequestParameters() - .withContents(tableWithHeader("Parameter", "Description") - .row("`a`", "one").row("`b`", "two")); new RequestParametersSnippet( Arrays.asList(parameterWithName("a").description("one"), parameterWithName("b").description("two"))).document( this.operationBuilder.request("http://localhost") .param("a", "bravo").param("b", "bravo").build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description").row("`a`", "one") + .row("`b`", "two")); } @Test public void requestParameterWithNoValue() throws IOException { - this.snippets.expectRequestParameters().withContents( - tableWithHeader("Parameter", "Description").row("`a`", "one")); new RequestParametersSnippet( Arrays.asList(parameterWithName("a").description("one"))) .document(this.operationBuilder.request("http://localhost") .param("a").build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); } @Test public void ignoredRequestParameter() throws IOException { - this.snippets.expectRequestParameters().withContents( - tableWithHeader("Parameter", "Description").row("`b`", "two")); new RequestParametersSnippet(Arrays.asList(parameterWithName("a").ignored(), parameterWithName("b").description("two"))) .document(this.operationBuilder.request("http://localhost") .param("a", "bravo").param("b", "bravo").build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description").row("`b`", "two")); } @Test public void allUndocumentedRequestParametersCanBeIgnored() throws IOException { - this.snippets.expectRequestParameters().withContents( - tableWithHeader("Parameter", "Description").row("`b`", "two")); new RequestParametersSnippet( Arrays.asList(parameterWithName("b").description("two")), true) .document(this.operationBuilder.request("http://localhost") .param("a", "bravo").param("b", "bravo").build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description").row("`b`", "two")); } @Test public void missingOptionalRequestParameter() throws IOException { - this.snippets.expectRequestParameters() - .withContents(tableWithHeader("Parameter", "Description") - .row("`a`", "one").row("`b`", "two")); new RequestParametersSnippet( Arrays.asList(parameterWithName("a").description("one").optional(), parameterWithName("b").description("two"))).document( this.operationBuilder.request("http://localhost") .param("b", "bravo").build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description").row("`a`", "one") + .row("`b`", "two")); } @Test public void presentOptionalRequestParameter() throws IOException { - this.snippets.expectRequestParameters().withContents( - tableWithHeader("Parameter", "Description").row("`a`", "one")); new RequestParametersSnippet( Arrays.asList(parameterWithName("a").description("one").optional())) .document(this.operationBuilder.request("http://localhost") .param("a", "one").build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description").row("`a`", "one")); } @Test @@ -115,8 +115,6 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) .willReturn(snippetResource("request-parameters-with-title")); - this.snippets.expectRequestParameters().withContents(containsString("The title")); - new RequestParametersSnippet(Arrays.asList( parameterWithName("a").description("one") .attributes(key("foo").value("alpha")), @@ -128,6 +126,7 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { new MustacheTemplateEngine(resolver)) .request("http://localhost").param("a", "alpha") .param("b", "bravo").build()); + assertThat(this.generatedSnippets.requestParameters()).contains("The title"); } @Test @@ -135,10 +134,6 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) .willReturn(snippetResource("request-parameters-with-extra-column")); - this.snippets.expectRequestParameters() - .withContents(tableWithHeader("Parameter", "Description", "Foo") - .row("a", "one", "alpha").row("b", "two", "bravo")); - new RequestParametersSnippet(Arrays.asList( parameterWithName("a").description("one") .attributes(key("foo").value("alpha")), @@ -152,6 +147,9 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { .request("http://localhost") .param("a", "alpha").param("b", "bravo") .build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description", "Foo") + .row("a", "one", "alpha").row("b", "two", "bravo")); } @Test @@ -159,10 +157,6 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parameters")) .willReturn(snippetResource("request-parameters-with-optional-column")); - this.snippets.expectRequestParameters() - .withContents(tableWithHeader("Parameter", "Optional", "Description") - .row("a", "true", "one").row("b", "false", "two")); - new RequestParametersSnippet( Arrays.asList(parameterWithName("a").description("one").optional(), parameterWithName("b").description("two"))) @@ -174,29 +168,31 @@ public class RequestParametersSnippetTests extends AbstractSnippetTests { .request("http://localhost") .param("a", "alpha").param("b", "bravo") .build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Optional", "Description") + .row("a", "true", "one").row("b", "false", "two")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectRequestParameters() - .withContents(tableWithHeader("Parameter", "Description") - .row("`a`", "one").row("`b`", "two")); RequestDocumentation.requestParameters(parameterWithName("a").description("one")) .and(parameterWithName("b").description("two")) .document(this.operationBuilder.request("http://localhost") .param("a", "bravo").param("b", "bravo").build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description").row("`a`", "one") + .row("`b`", "two")); } @Test public void requestParametersWithEscapedContent() throws IOException { - this.snippets.expectRequestParameters() - .withContents(tableWithHeader("Parameter", "Description").row( - escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); - RequestDocumentation .requestParameters(parameterWithName("Foo|Bar").description("one|two")) .document(this.operationBuilder.request("http://localhost") .param("Foo|Bar", "baz").build()); + assertThat(this.generatedSnippets.requestParameters()) + .is(tableWithHeader("Parameter", "Description").row( + escapeIfNecessary("`Foo|Bar`"), escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java index 935e2d02..63888490 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetFailureTests.java @@ -25,7 +25,6 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.springframework.restdocs.snippet.SnippetException; -import org.springframework.restdocs.test.ExpectedSnippets; import org.springframework.restdocs.test.OperationBuilder; import static org.hamcrest.CoreMatchers.equalTo; @@ -43,9 +42,6 @@ public class RequestPartsSnippetFailureTests { @Rule public OperationBuilder operationBuilder = new OperationBuilder(asciidoctor()); - @Rule - public ExpectedSnippets snippets = new ExpectedSnippets(asciidoctor()); - @Rule public ExpectedException thrown = ExpectedException.none(); diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java index 9abbd4ac..757119ed 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/request/RequestPartsSnippetTests.java @@ -28,7 +28,7 @@ import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.restdocs.templates.TemplateResourceResolver; import org.springframework.restdocs.templates.mustache.MustacheTemplateEngine; -import static org.hamcrest.CoreMatchers.containsString; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.request.RequestDocumentation.partWithName; @@ -48,57 +48,57 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { @Test public void requestParts() throws IOException { - this.snippets.expectRequestParts() - .withContents(tableWithHeader("Part", "Description").row("`a`", "one") - .row("`b`", "two")); new RequestPartsSnippet(Arrays.asList(partWithName("a").description("one"), partWithName("b").description("two"))) .document(this.operationBuilder.request("http://localhost") .part("a", "bravo".getBytes()).and() .part("b", "bravo".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", + "two")); } @Test public void ignoredRequestPart() throws IOException { - this.snippets.expectRequestParts() - .withContents(tableWithHeader("Part", "Description").row("`b`", "two")); new RequestPartsSnippet(Arrays.asList(partWithName("a").ignored(), partWithName("b").description("two"))) .document(this.operationBuilder.request("http://localhost") .part("a", "bravo".getBytes()).and() .part("b", "bravo".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Description").row("`b`", "two")); } @Test public void allUndocumentedRequestPartsCanBeIgnored() throws IOException { - this.snippets.expectRequestParts() - .withContents(tableWithHeader("Part", "Description").row("`b`", "two")); new RequestPartsSnippet(Arrays.asList(partWithName("b").description("two")), true) .document(this.operationBuilder.request("http://localhost") .part("a", "bravo".getBytes()).and().part("b", "bravo".getBytes()) .build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Description").row("`b`", "two")); } @Test public void missingOptionalRequestPart() throws IOException { - this.snippets.expectRequestParts() - .withContents(tableWithHeader("Part", "Description").row("`a`", "one") - .row("`b`", "two")); new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two"))).document( this.operationBuilder.request("http://localhost") .part("b", "bravo".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", + "two")); } @Test public void presentOptionalRequestPart() throws IOException { - this.snippets.expectRequestParts() - .withContents(tableWithHeader("Part", "Description").row("`a`", "one")); new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").optional())) .document(this.operationBuilder.request("http://localhost") .part("a", "one".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Description").row("`a`", "one")); } @Test @@ -106,8 +106,6 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parts")) .willReturn(snippetResource("request-parts-with-title")); - this.snippets.expectRequestParts().withContents(containsString("The title")); - new RequestPartsSnippet(Arrays.asList( partWithName("a").description("one") .attributes(key("foo").value("alpha")), @@ -119,6 +117,7 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { new MustacheTemplateEngine(resolver)) .request("http://localhost").part("a", "alpha".getBytes()) .and().part("b", "bravo".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()).contains("The title"); } @Test @@ -126,10 +125,6 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parts")) .willReturn(snippetResource("request-parts-with-extra-column")); - this.snippets.expectRequestParts() - .withContents(tableWithHeader("Part", "Description", "Foo") - .row("a", "one", "alpha").row("b", "two", "bravo")); - new RequestPartsSnippet(Arrays.asList( partWithName("a").description("one") .attributes(key("foo").value("alpha")), @@ -143,6 +138,9 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { .request("http://localhost") .part("a", "alpha".getBytes()).and() .part("b", "bravo".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Description", "Foo").row("a", "one", "alpha") + .row("b", "two", "bravo")); } @Test @@ -150,10 +148,6 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { TemplateResourceResolver resolver = mock(TemplateResourceResolver.class); given(resolver.resolveTemplateResource("request-parts")) .willReturn(snippetResource("request-parts-with-optional-column")); - this.snippets.expectRequestParts() - .withContents(tableWithHeader("Part", "Optional", "Description") - .row("a", "true", "one").row("b", "false", "two")); - new RequestPartsSnippet( Arrays.asList(partWithName("a").description("one").optional(), partWithName("b").description("two"))) @@ -165,29 +159,31 @@ public class RequestPartsSnippetTests extends AbstractSnippetTests { .request("http://localhost") .part("a", "alpha".getBytes()).and() .part("b", "bravo".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Optional", "Description") + .row("a", "true", "one").row("b", "false", "two")); } @Test public void additionalDescriptors() throws IOException { - this.snippets.expectRequestParts() - .withContents(tableWithHeader("Part", "Description").row("`a`", "one") - .row("`b`", "two")); RequestDocumentation.requestParts(partWithName("a").description("one")) .and(partWithName("b").description("two")) .document(this.operationBuilder.request("http://localhost") .part("a", "bravo".getBytes()).and().part("b", "bravo".getBytes()) .build()); + assertThat(this.generatedSnippets.requestParts()) + .is(tableWithHeader("Part", "Description").row("`a`", "one").row("`b`", + "two")); } @Test public void requestPartsWithEscapedContent() throws IOException { - this.snippets.expectRequestParts().withContents( - tableWithHeader("Part", "Description").row(escapeIfNecessary("`Foo|Bar`"), - escapeIfNecessary("one|two"))); - RequestDocumentation.requestParts(partWithName("Foo|Bar").description("one|two")) .document(this.operationBuilder.request("http://localhost") .part("Foo|Bar", "baz".getBytes()).build()); + assertThat(this.generatedSnippets.requestParts()).is( + tableWithHeader("Part", "Description").row(escapeIfNecessary("`Foo|Bar`"), + escapeIfNecessary("one|two"))); } private String escapeIfNecessary(String input) { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java index 83f96e61..36059de0 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/RestDocumentationContextPlaceholderResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,7 @@ import org.springframework.restdocs.ManualRestDocumentation; import org.springframework.restdocs.RestDocumentationContext; import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RestDocumentationContextPlaceholderResolver}. @@ -35,43 +34,45 @@ public class RestDocumentationContextPlaceholderResolverTests { @Test public void kebabCaseMethodName() throws Exception { - assertThat(createResolver("dashSeparatedMethodName").resolvePlaceholder( - "method-name"), equalTo("dash-separated-method-name")); + assertThat(createResolver("dashSeparatedMethodName") + .resolvePlaceholder("method-name")) + .isEqualTo("dash-separated-method-name"); } @Test public void snakeCaseMethodName() throws Exception { - assertThat(createResolver("underscoreSeparatedMethodName").resolvePlaceholder( - "method_name"), equalTo("underscore_separated_method_name")); + assertThat(createResolver("underscoreSeparatedMethodName") + .resolvePlaceholder("method_name")) + .isEqualTo("underscore_separated_method_name"); } @Test public void camelCaseMethodName() throws Exception { - assertThat(createResolver("camelCaseMethodName").resolvePlaceholder("methodName"), - equalTo("camelCaseMethodName")); + assertThat(createResolver("camelCaseMethodName").resolvePlaceholder("methodName")) + .isEqualTo("camelCaseMethodName"); } @Test public void kebabCaseClassName() throws Exception { - assertThat(createResolver().resolvePlaceholder("class-name"), - equalTo("rest-documentation-context-placeholder-resolver-tests")); + assertThat(createResolver().resolvePlaceholder("class-name")) + .isEqualTo("rest-documentation-context-placeholder-resolver-tests"); } @Test public void snakeCaseClassName() throws Exception { - assertThat(createResolver().resolvePlaceholder("class_name"), - equalTo("rest_documentation_context_placeholder_resolver_tests")); + assertThat(createResolver().resolvePlaceholder("class_name")) + .isEqualTo("rest_documentation_context_placeholder_resolver_tests"); } @Test public void camelCaseClassName() throws Exception { - assertThat(createResolver().resolvePlaceholder("ClassName"), - equalTo("RestDocumentationContextPlaceholderResolverTests")); + assertThat(createResolver().resolvePlaceholder("ClassName")) + .isEqualTo("RestDocumentationContextPlaceholderResolverTests"); } @Test public void stepCount() throws Exception { - assertThat(createResolver("stepCount").resolvePlaceholder("step"), equalTo("1")); + assertThat(createResolver("stepCount").resolvePlaceholder("step")).isEqualTo("1"); } private PlaceholderResolver createResolver() { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java index 9dc871a1..bae92597 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/StandardWriterResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,9 +30,7 @@ import org.springframework.restdocs.RestDocumentationContext; import org.springframework.util.FileCopyUtils; import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor; @@ -56,29 +54,26 @@ public class StandardWriterResolverTests { @Test public void absoluteInput() { String absolutePath = new File("foo").getAbsolutePath(); - assertThat( - this.resolver.resolveFile(absolutePath, "bar.txt", - createContext(absolutePath)), - is(new File(absolutePath, "bar.txt"))); + assertThat(this.resolver.resolveFile(absolutePath, "bar.txt", + createContext(absolutePath))) + .isEqualTo(new File(absolutePath, "bar.txt")); } @Test public void configuredOutputAndRelativeInput() { File outputDir = new File("foo").getAbsoluteFile(); - assertThat( - this.resolver.resolveFile("bar", "baz.txt", - createContext(outputDir.getAbsolutePath())), - is(new File(outputDir, "bar/baz.txt"))); + assertThat(this.resolver.resolveFile("bar", "baz.txt", + createContext(outputDir.getAbsolutePath()))) + .isEqualTo(new File(outputDir, "bar/baz.txt")); } @Test public void configuredOutputAndAbsoluteInput() { File outputDir = new File("foo").getAbsoluteFile(); String absolutePath = new File("bar").getAbsolutePath(); - assertThat( - this.resolver.resolveFile(absolutePath, "baz.txt", - createContext(outputDir.getAbsolutePath())), - is(new File(absolutePath, "baz.txt"))); + assertThat(this.resolver.resolveFile(absolutePath, "baz.txt", + createContext(outputDir.getAbsolutePath()))) + .isEqualTo(new File(absolutePath, "baz.txt")); } @Test @@ -117,9 +112,9 @@ public class StandardWriterResolverTests { throws IOException { writer.write("test"); writer.flush(); - assertThat(expectedLocation.exists(), is(true)); - assertThat(FileCopyUtils.copyToString(new FileReader(expectedLocation)), - is(equalTo("test"))); + assertThat(expectedLocation).exists(); + assertThat(FileCopyUtils.copyToString(new FileReader(expectedLocation))) + .isEqualTo("test"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java index af87277f..a1853d72 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/snippet/TemplatedSnippetTests.java @@ -26,15 +26,10 @@ import org.junit.Test; import org.springframework.restdocs.operation.Operation; import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.restdocs.test.ExpectedSnippets; +import org.springframework.restdocs.test.GeneratedSnippets; import org.springframework.restdocs.test.OperationBuilder; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link TemplatedSnippet}. @@ -48,7 +43,7 @@ public class TemplatedSnippetTests { TemplateFormats.asciidoctor()); @Rule - public ExpectedSnippets snippets = new ExpectedSnippets( + public GeneratedSnippets snippets = new GeneratedSnippets( TemplateFormats.asciidoctor()); @Test @@ -57,30 +52,30 @@ public class TemplatedSnippetTests { attributes.put("a", "alpha"); TemplatedSnippet snippet = new TestTemplatedSnippet(attributes); attributes.put("b", "bravo"); - assertThat(snippet.getAttributes().size(), is(1)); - assertThat(snippet.getAttributes(), hasEntry("a", (Object) "alpha")); + assertThat(snippet.getAttributes()).hasSize(1); + assertThat(snippet.getAttributes()).containsEntry("a", "alpha"); } @Test public void nullAttributesAreTolerated() { - assertThat(new TestTemplatedSnippet(null).getAttributes(), is(not(nullValue()))); - assertThat(new TestTemplatedSnippet(null).getAttributes().size(), is(0)); + assertThat(new TestTemplatedSnippet(null).getAttributes()).isNotNull(); + assertThat(new TestTemplatedSnippet(null).getAttributes()).isEmpty(); } @Test public void snippetName() { assertThat(new TestTemplatedSnippet(Collections.emptyMap()) - .getSnippetName(), is(equalTo("test"))); + .getSnippetName()).isEqualTo("test"); } @Test public void multipleSnippetsCanBeProducedFromTheSameTemplate() throws IOException { - this.snippets.expect("multiple-snippets-one"); - this.snippets.expect("multiple-snippets-two"); new TestTemplatedSnippet("one", "multiple-snippets") .document(this.operationBuilder.build()); new TestTemplatedSnippet("two", "multiple-snippets") .document(this.operationBuilder.build()); + assertThat(this.snippets.snippet("multiple-snippets-one")).isNotNull(); + assertThat(this.snippets.snippet("multiple-snippets-two")).isNotNull(); } private static class TestTemplatedSnippet extends TemplatedSnippet { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java index b8f9bd64..bd0484fa 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/StandardTemplateResourceResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,9 +27,8 @@ import org.junit.rules.ExpectedException; import org.springframework.core.io.Resource; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor; /** @@ -69,8 +68,8 @@ public class StandardTemplateResourceResolverTests { }); - assertThat(snippet.getURL(), is( - equalTo(getClass().getResource("test-format-specific-custom.snippet")))); + assertThat(snippet.getURL()) + .isEqualTo(getClass().getResource("test-format-specific-custom.snippet")); } @Test @@ -93,8 +92,8 @@ public class StandardTemplateResourceResolverTests { }); - assertThat(snippet.getURL(), - is(equalTo(getClass().getResource("test-custom.snippet")))); + assertThat(snippet.getURL()) + .isEqualTo(getClass().getResource("test-custom.snippet")); } @Test @@ -113,8 +112,8 @@ public class StandardTemplateResourceResolverTests { }); - assertThat(snippet.getURL(), - is(equalTo(getClass().getResource("test-default.snippet")))); + assertThat(snippet.getURL()) + .isEqualTo(getClass().getResource("test-default.snippet")); } @Test diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/mustache/AsciidoctorTableCellContentLambdaTests.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/mustache/AsciidoctorTableCellContentLambdaTests.java index c9420919..549be7f1 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/mustache/AsciidoctorTableCellContentLambdaTests.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/templates/mustache/AsciidoctorTableCellContentLambdaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,7 @@ import org.junit.Test; import org.springframework.restdocs.mustache.Template.Fragment; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -42,7 +40,7 @@ public class AsciidoctorTableCellContentLambdaTests { given(fragment.execute()).willReturn("|foo|bar|baz|"); StringWriter writer = new StringWriter(); new AsciidoctorTableCellContentLambda().execute(fragment, writer); - assertThat(writer.toString(), is(equalTo("\\|foo\\|bar\\|baz\\|"))); + assertThat(writer.toString()).isEqualTo("\\|foo\\|bar\\|baz\\|"); } @Test @@ -51,7 +49,7 @@ public class AsciidoctorTableCellContentLambdaTests { given(fragment.execute()).willReturn("\\|foo|bar\\|baz|"); StringWriter writer = new StringWriter(); new AsciidoctorTableCellContentLambda().execute(fragment, writer); - assertThat(writer.toString(), is(equalTo("\\|foo\\|bar\\|baz\\|"))); + assertThat(writer.toString()).isEqualTo("\\|foo\\|bar\\|baz\\|"); } } diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/ExpectedSnippets.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/ExpectedSnippets.java deleted file mode 100644 index 3a174532..00000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/ExpectedSnippets.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright 2014-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.restdocs.test; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.hamcrest.Matcher; -import org.junit.runners.model.Statement; - -import org.springframework.restdocs.snippet.TemplatedSnippet; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.test.SnippetMatchers.SnippetMatcher; - -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -/** - * The {@code ExpectedSnippets} rule is used to verify that a test of a - * {@link TemplatedSnippet} has generated the expected snippets. - * - * @author Andy Wilkinson - * @author Andreas Evers - */ -public class ExpectedSnippets extends OperationTestRule { - - private final TemplateFormat templateFormat; - - private String operationName; - - private File outputDirectory; - - private List expectations = new ArrayList<>(); - - public ExpectedSnippets(TemplateFormat templateFormat) { - this.templateFormat = templateFormat; - } - - @Override - public Statement apply(final Statement base, File outputDirectory, - String operationName) { - this.outputDirectory = outputDirectory; - this.operationName = operationName; - return new ExpectedSnippetsStatement(base); - } - - private void verifySnippets() throws IOException { - if (this.outputDirectory != null && this.operationName != null) { - File snippetDir = new File(this.outputDirectory, this.operationName); - for (ExpectedSnippet expectation : this.expectations) { - expectation.verify(snippetDir); - } - } - } - - public ExpectedSnippet expectCurlRequest() { - return expect("curl-request"); - } - - public ExpectedSnippet expectHttpieRequest() { - return expect("httpie-request"); - } - - public ExpectedSnippet expectRequestFields() { - return expect("request-fields"); - } - - public ExpectedSnippet expectRequestPartFields(String partName) { - return expect("request-part-" + partName + "-fields"); - } - - public ExpectedSnippet expectResponseFields() { - return expect("response-fields"); - } - - public ExpectedSnippet expectRequestHeaders() { - return expect("request-headers"); - } - - public ExpectedSnippet expectResponseHeaders() { - return expect("response-headers"); - } - - public ExpectedSnippet expectLinks() { - return expect("links"); - } - - public ExpectedSnippet expectHttpRequest() { - return expect("http-request"); - } - - public ExpectedSnippet expectHttpResponse() { - return expect("http-response"); - } - - public ExpectedSnippet expectRequestParameters() { - return expect("request-parameters"); - } - - public ExpectedSnippet expectPathParameters() { - return expect("path-parameters"); - } - - public ExpectedSnippet expectRequestParts() { - return expect("request-parts"); - } - - public ExpectedSnippet expect(String type) { - ExpectedSnippet expectedSnippet = new ExpectedSnippet( - SnippetMatchers.snippet(this.templateFormat), type); - this.expectations.add(expectedSnippet); - return expectedSnippet; - } - - public File getOutputDirectory() { - return this.outputDirectory; - } - - public String getOperationName() { - return this.operationName; - } - - /** - * Expecations for a particular snippet. - */ - public final class ExpectedSnippet { - - private final SnippetMatcher snippetMatcher; - - private final String snippetName; - - private ExpectedSnippet(SnippetMatcher snippetMatcher, String snippetName) { - this.snippetMatcher = snippetMatcher; - this.snippetName = snippetName; - } - - private void verify(File snippetDir) { - File snippetFile = new File(snippetDir, this.snippetName + "." - + ExpectedSnippets.this.templateFormat.getFileExtension()); - assertThat(snippetFile, is(this.snippetMatcher)); - } - - public void withContents(Matcher matcher) { - this.snippetMatcher.withContents(matcher); - } - - } - - private final class ExpectedSnippetsStatement extends Statement { - - private final Statement delegate; - - private ExpectedSnippetsStatement(Statement delegate) { - this.delegate = delegate; - } - - @Override - public void evaluate() throws Throwable { - this.delegate.evaluate(); - verifySnippets(); - } - - } - -} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/GeneratedSnippets.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/GeneratedSnippets.java new file mode 100644 index 00000000..2c141f56 --- /dev/null +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/GeneratedSnippets.java @@ -0,0 +1,132 @@ +/* + * Copyright 2014-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.restdocs.test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +import org.junit.runners.model.Statement; + +import org.springframework.restdocs.templates.TemplateFormat; +import org.springframework.util.FileCopyUtils; + +import static org.assertj.core.api.Assertions.fail; + +/** + * The {@code GeneratedSnippets} rule is used to capture the snippets generated by a test + * and assert their existence and content. + * + * @author Andy Wilkinson + * @author Andreas Evers + */ +public class GeneratedSnippets extends OperationTestRule { + + private final TemplateFormat templateFormat; + + private String operationName; + + private File outputDirectory; + + public GeneratedSnippets(TemplateFormat templateFormat) { + this.templateFormat = templateFormat; + } + + @Override + public Statement apply(Statement base, File outputDirectory, String operationName) { + this.outputDirectory = outputDirectory; + this.operationName = operationName; + return base; + } + + public String curlRequest() { + return snippet("curl-request"); + } + + public String httpieRequest() { + return snippet("httpie-request"); + } + + public String requestHeaders() { + return snippet("request-headers"); + } + + public String responseHeaders() { + return snippet("response-headers"); + } + + public String httpRequest() { + return snippet("http-request"); + } + + public String httpResponse() { + return snippet("http-response"); + } + + public String links() { + return snippet("links"); + } + + public String requestFields() { + return snippet("request-fields"); + } + + public String requestParts() { + return snippet("request-parts"); + } + + public String requestPartFields(String partName) { + return snippet("request-part-" + partName + "-fields"); + } + + public String responseFields() { + return snippet("response-fields"); + } + + public String pathParameters() { + return snippet("path-parameters"); + } + + public String requestParameters() { + return snippet("request-parameters"); + } + + public String snippet(String name) { + File snippetFile = getSnippetFile(name); + try { + return FileCopyUtils.copyToString(new InputStreamReader( + new FileInputStream(snippetFile), StandardCharsets.UTF_8)); + } + catch (Exception ex) { + fail("Failed to read '" + snippetFile + "'", ex); + return null; + } + } + + private File getSnippetFile(String name) { + if (this.outputDirectory == null) { + fail("Output directory was null"); + } + if (this.operationName == null) { + fail("Operation name was null"); + } + File snippetDir = new File(this.outputDirectory, this.operationName); + return new File(snippetDir, name + "." + this.templateFormat.getFileExtension()); + } + +} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OutputCapture.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OutputCapture.java index e7b4ef75..f2f93115 100644 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OutputCapture.java +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/OutputCapture.java @@ -23,13 +23,14 @@ import java.io.PrintStream; import java.util.ArrayList; import java.util.List; +import org.assertj.core.api.HamcrestCondition; import org.hamcrest.Matcher; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; +import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.allOf; -import static org.junit.Assert.assertThat; /** * JUnit {@code @Rule} to capture output from System.out and System.err. @@ -59,8 +60,8 @@ public class OutputCapture implements TestRule { finally { try { if (!OutputCapture.this.matchers.isEmpty()) { - assertThat(getOutputAsString(), - allOf(OutputCapture.this.matchers)); + assertThat(getOutputAsString()).is(new HamcrestCondition<>( + allOf(OutputCapture.this.matchers))); } } finally { diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetConditions.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetConditions.java new file mode 100644 index 00000000..137f6b05 --- /dev/null +++ b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetConditions.java @@ -0,0 +1,370 @@ +/* + * Copyright 2014-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.restdocs.test; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.assertj.core.api.Condition; +import org.assertj.core.description.Description; + +import org.springframework.http.HttpStatus; +import org.springframework.restdocs.templates.TemplateFormat; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * {@link Condition Conditions} for verify the contents of generated documentation + * snippets. + * + * @author Andy Wilkinson + */ +public final class SnippetConditions { + + private SnippetConditions() { + + } + + public static TableCondition tableWithHeader(TemplateFormat format, + String... headers) { + if ("adoc".equals(format.getFileExtension())) { + return new AsciidoctorTableCondition(null, headers); + } + return new MarkdownTableCondition(null, headers); + } + + public static TableCondition tableWithTitleAndHeader(TemplateFormat format, + String title, String... headers) { + if ("adoc".equals(format.getFileExtension())) { + return new AsciidoctorTableCondition(title, headers); + } + return new MarkdownTableCondition(title, headers); + } + + public static HttpRequestCondition httpRequest(TemplateFormat format, + RequestMethod requestMethod, String uri) { + if ("adoc".equals(format.getFileExtension())) { + return new HttpRequestCondition(requestMethod, uri, + new AsciidoctorCodeBlockCondition<>("http", "nowrap"), 3); + } + return new HttpRequestCondition(requestMethod, uri, + new MarkdownCodeBlockCondition<>("http"), 2); + } + + public static HttpResponseCondition httpResponse(TemplateFormat format, + HttpStatus status) { + if ("adoc".equals(format.getFileExtension())) { + return new HttpResponseCondition(status, + new AsciidoctorCodeBlockCondition<>("http", "nowrap"), 3); + } + return new HttpResponseCondition(status, new MarkdownCodeBlockCondition<>("http"), + 2); + } + + @SuppressWarnings({ "rawtypes" }) + public static CodeBlockCondition codeBlock(TemplateFormat format, + String language) { + if ("adoc".equals(format.getFileExtension())) { + return new AsciidoctorCodeBlockCondition(language, null); + } + return new MarkdownCodeBlockCondition(language); + } + + @SuppressWarnings({ "rawtypes" }) + public static CodeBlockCondition codeBlock(TemplateFormat format, String language, + String options) { + if ("adoc".equals(format.getFileExtension())) { + return new AsciidoctorCodeBlockCondition(language, options); + } + return new MarkdownCodeBlockCondition(language); + } + + private static abstract class AbstractSnippetContentCondition + extends Condition { + + private List lines = new ArrayList<>(); + + protected AbstractSnippetContentCondition() { + as(new Description() { + + @Override + public String value() { + return getLinesAsString(); + } + + }); + } + + protected void addLine(String line) { + this.lines.add(line); + } + + protected void addLine(int index, String line) { + this.lines.add(determineIndex(index), line); + } + + private int determineIndex(int index) { + if (index >= 0) { + return index; + } + return index + this.lines.size(); + } + + @Override + public boolean matches(String content) { + return getLinesAsString().equals(content); + } + + private String getLinesAsString() { + StringWriter writer = new StringWriter(); + Iterator iterator = this.lines.iterator(); + while (iterator.hasNext()) { + writer.append(String.format("%s", iterator.next())); + if (iterator.hasNext()) { + writer.append(String.format("%n")); + } + } + return writer.toString(); + } + } + + /** + * Base class for code block Conditions. + * + * @param The type of the Condition + */ + public static class CodeBlockCondition> + extends AbstractSnippetContentCondition { + + @SuppressWarnings("unchecked") + public T withContent(String content) { + this.addLine(-1, content); + return (T) this; + } + + } + + /** + * A {@link Condition} for an Asciidoctor code block. + * + * @param The type of the Condition + */ + public static class AsciidoctorCodeBlockCondition> + extends CodeBlockCondition { + + protected AsciidoctorCodeBlockCondition(String language, String options) { + this.addLine("[source" + (language == null ? "" : "," + language) + + (options == null ? "" : ",options=\"" + options + "\"") + "]"); + this.addLine("----"); + this.addLine("----"); + } + + } + + /** + * A {@link Condition} for a Markdown code block. + * + * @param The type of the Condition + */ + public static class MarkdownCodeBlockCondition> + extends CodeBlockCondition { + + protected MarkdownCodeBlockCondition(String language) { + this.addLine("```" + (language == null ? "" : language)); + this.addLine("```"); + } + + } + + /** + * A {@link Condition} for an HTTP request or response. + * + * @param The type of the Condition + */ + public static abstract class HttpCondition> + extends Condition { + + private final CodeBlockCondition delegate; + + private int headerOffset; + + protected HttpCondition(CodeBlockCondition delegate, int headerOffset) { + this.delegate = delegate; + this.headerOffset = headerOffset; + } + + @SuppressWarnings("unchecked") + public T header(String name, String value) { + this.delegate.addLine(this.headerOffset++, name + ": " + value); + return (T) this; + } + + @SuppressWarnings("unchecked") + public T header(String name, long value) { + this.delegate.addLine(this.headerOffset++, name + ": " + value); + return (T) this; + } + + @SuppressWarnings("unchecked") + public T content(String content) { + this.delegate.addLine(-1, content); + return (T) this; + } + + @Override + public boolean matches(String item) { + return this.delegate.matches(item); + } + + // @Override + // public void describeTo(Description description) { + // this.delegate.describeTo(description); + // } + + } + + /** + * A {@link Condition} for an HTTP response. + */ + public static final class HttpResponseCondition + extends HttpCondition { + + private HttpResponseCondition(HttpStatus status, CodeBlockCondition delegate, + int headerOffset) { + super(delegate, headerOffset); + this.content("HTTP/1.1 " + status.value() + " " + status.getReasonPhrase()); + this.content(""); + } + + } + + /** + * A {@link Condition} for an HTTP request. + */ + public static final class HttpRequestCondition + extends HttpCondition { + + private HttpRequestCondition(RequestMethod requestMethod, String uri, + CodeBlockCondition delegate, int headerOffset) { + super(delegate, headerOffset); + this.content(requestMethod.name() + " " + uri + " HTTP/1.1"); + this.content(""); + } + + } + + /** + * Base class for table Conditions. + * + * @param The concrete type of the Condition + */ + public static abstract class TableCondition> + extends AbstractSnippetContentCondition { + + public abstract T row(String... entries); + + public abstract T configuration(String configuration); + + } + + /** + * A {@link Condition} for an Asciidoctor table. + */ + public static final class AsciidoctorTableCondition + extends TableCondition { + + private AsciidoctorTableCondition(String title, String... columns) { + if (StringUtils.hasText(title)) { + this.addLine("." + title); + } + this.addLine("|==="); + String header = "|" + StringUtils + .collectionToDelimitedString(Arrays.asList(columns), "|"); + this.addLine(header); + this.addLine(""); + this.addLine("|==="); + } + + @Override + public AsciidoctorTableCondition row(String... entries) { + for (String entry : entries) { + this.addLine(-1, "|" + escapeEntry(entry)); + } + this.addLine(-1, ""); + return this; + } + + private String escapeEntry(String entry) { + if (entry.startsWith("`") && entry.endsWith("`")) { + return "`+" + entry.substring(1, entry.length() - 1) + "+`"; + } + return entry; + } + + @Override + public AsciidoctorTableCondition configuration(String configuration) { + this.addLine(0, configuration); + return this; + } + + } + + /** + * A {@link Condition} for a Markdown table. + */ + public static final class MarkdownTableCondition + extends TableCondition { + + private MarkdownTableCondition(String title, String... columns) { + if (StringUtils.hasText(title)) { + this.addLine(title); + this.addLine(""); + } + String header = StringUtils + .collectionToDelimitedString(Arrays.asList(columns), " | "); + this.addLine(header); + List components = new ArrayList<>(); + for (String column : columns) { + StringBuilder dashes = new StringBuilder(); + for (int i = 0; i < column.length(); i++) { + dashes.append("-"); + } + components.add(dashes.toString()); + } + this.addLine(StringUtils.collectionToDelimitedString(components, " | ")); + this.addLine(""); + } + + @Override + public MarkdownTableCondition row(String... entries) { + this.addLine(-1, StringUtils + .collectionToDelimitedString(Arrays.asList(entries), " | ")); + return this; + } + + @Override + public MarkdownTableCondition configuration(String configuration) { + throw new UnsupportedOperationException( + "Markdown does not support table configuration"); + } + + } + +} diff --git a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetMatchers.java b/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetMatchers.java deleted file mode 100644 index 3ac67a08..00000000 --- a/spring-restdocs-core/src/test/java/org/springframework/restdocs/test/SnippetMatchers.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * Copyright 2014-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.restdocs.test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.Matcher; - -import org.springframework.http.HttpStatus; -import org.springframework.restdocs.templates.TemplateFormat; -import org.springframework.restdocs.templates.TemplateFormats; -import org.springframework.util.FileCopyUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.RequestMethod; - -/** - * {@link Matcher Matchers} for verify the contents of generated documentation snippets. - * - * @author Andy Wilkinson - */ -public final class SnippetMatchers { - - private SnippetMatchers() { - - } - - public static SnippetMatcher snippet(TemplateFormat templateFormat) { - return new SnippetMatcher(templateFormat); - } - - public static TableMatcher tableWithHeader(TemplateFormat format, - String... headers) { - if ("adoc".equals(format.getFileExtension())) { - return new AsciidoctorTableMatcher(null, headers); - } - return new MarkdownTableMatcher(null, headers); - } - - public static TableMatcher tableWithTitleAndHeader(TemplateFormat format, - String title, String... headers) { - if ("adoc".equals(format.getFileExtension())) { - return new AsciidoctorTableMatcher(title, headers); - } - return new MarkdownTableMatcher(title, headers); - } - - public static HttpRequestMatcher httpRequest(TemplateFormat format, - RequestMethod requestMethod, String uri) { - if ("adoc".equals(format.getFileExtension())) { - return new HttpRequestMatcher(requestMethod, uri, - new AsciidoctorCodeBlockMatcher<>("http", "nowrap"), 3); - } - return new HttpRequestMatcher(requestMethod, uri, - new MarkdownCodeBlockMatcher<>("http"), 2); - } - - public static HttpResponseMatcher httpResponse(TemplateFormat format, - HttpStatus status) { - if ("adoc".equals(format.getFileExtension())) { - return new HttpResponseMatcher(status, - new AsciidoctorCodeBlockMatcher<>("http", "nowrap"), 3); - } - return new HttpResponseMatcher(status, new MarkdownCodeBlockMatcher<>("http"), 2); - } - - @SuppressWarnings({ "rawtypes" }) - public static CodeBlockMatcher codeBlock(TemplateFormat format, String language) { - if ("adoc".equals(format.getFileExtension())) { - return new AsciidoctorCodeBlockMatcher(language, null); - } - return new MarkdownCodeBlockMatcher(language); - } - - @SuppressWarnings({ "rawtypes" }) - public static CodeBlockMatcher codeBlock(TemplateFormat format, String language, - String options) { - if ("adoc".equals(format.getFileExtension())) { - return new AsciidoctorCodeBlockMatcher(language, options); - } - return new MarkdownCodeBlockMatcher(language); - } - - private static abstract class AbstractSnippetContentMatcher - extends BaseMatcher { - - private final TemplateFormat templateFormat; - - private List lines = new ArrayList<>(); - - protected AbstractSnippetContentMatcher(TemplateFormat templateFormat) { - this.templateFormat = templateFormat; - } - - protected void addLine(String line) { - this.lines.add(line); - } - - protected void addLine(int index, String line) { - this.lines.add(determineIndex(index), line); - } - - private int determineIndex(int index) { - if (index >= 0) { - return index; - } - return index + this.lines.size(); - } - - @Override - public boolean matches(Object item) { - return getLinesAsString().equals(item); - } - - @Override - public void describeTo(Description description) { - description.appendText(this.templateFormat.getFileExtension() + " snippet"); - description.appendText(getLinesAsString()); - } - - @Override - public void describeMismatch(Object item, Description description) { - description.appendText("was:"); - if (item instanceof String) { - description.appendText((String) item); - } - else { - description.appendValue(item); - } - } - - private String getLinesAsString() { - StringWriter writer = new StringWriter(); - Iterator iterator = this.lines.iterator(); - while (iterator.hasNext()) { - writer.append(String.format("%s", iterator.next())); - if (iterator.hasNext()) { - writer.append(String.format("%n")); - } - } - return writer.toString(); - } - } - - /** - * Base class for code block matchers. - * - * @param The type of the matcher - */ - public static class CodeBlockMatcher> - extends AbstractSnippetContentMatcher { - - protected CodeBlockMatcher(TemplateFormat templateFormat) { - super(templateFormat); - } - - @SuppressWarnings("unchecked") - public T content(String content) { - this.addLine(-1, content); - return (T) this; - } - - } - - /** - * A {@link Matcher} for an Asciidoctor code block. - * - * @param The type of the matcher - */ - public static class AsciidoctorCodeBlockMatcher> - extends CodeBlockMatcher { - - protected AsciidoctorCodeBlockMatcher(String language, String options) { - super(TemplateFormats.asciidoctor()); - this.addLine("[source" + (language == null ? "" : "," + language) - + (options == null ? "" : ",options=\"" + options + "\"") + "]"); - this.addLine("----"); - this.addLine("----"); - } - - } - - /** - * A {@link Matcher} for a Markdown code block. - * - * @param The type of the matcher - */ - public static class MarkdownCodeBlockMatcher> - extends CodeBlockMatcher { - - protected MarkdownCodeBlockMatcher(String language) { - super(TemplateFormats.markdown()); - this.addLine("```" + (language == null ? "" : language)); - this.addLine("```"); - } - - } - - /** - * A {@link Matcher} for an HTTP request or response. - * - * @param The type of the matcher - */ - public static abstract class HttpMatcher> - extends BaseMatcher { - - private final CodeBlockMatcher delegate; - - private int headerOffset; - - protected HttpMatcher(CodeBlockMatcher delegate, int headerOffset) { - this.delegate = delegate; - this.headerOffset = headerOffset; - } - - @SuppressWarnings("unchecked") - public T header(String name, String value) { - this.delegate.addLine(this.headerOffset++, name + ": " + value); - return (T) this; - } - - @SuppressWarnings("unchecked") - public T header(String name, long value) { - this.delegate.addLine(this.headerOffset++, name + ": " + value); - return (T) this; - } - - @SuppressWarnings("unchecked") - public T content(String content) { - this.delegate.addLine(-1, content); - return (T) this; - } - - @Override - public boolean matches(Object item) { - return this.delegate.matches(item); - } - - @Override - public void describeTo(Description description) { - this.delegate.describeTo(description); - } - - } - - /** - * A {@link Matcher} for an HTTP response. - */ - public static final class HttpResponseMatcher - extends HttpMatcher { - - private HttpResponseMatcher(HttpStatus status, CodeBlockMatcher delegate, - int headerOffset) { - super(delegate, headerOffset); - this.content("HTTP/1.1 " + status.value() + " " + status.getReasonPhrase()); - this.content(""); - } - - } - - /** - * A {@link Matcher} for an HTTP request. - */ - public static final class HttpRequestMatcher extends HttpMatcher { - - private HttpRequestMatcher(RequestMethod requestMethod, String uri, - CodeBlockMatcher delegate, int headerOffset) { - super(delegate, headerOffset); - this.content(requestMethod.name() + " " + uri + " HTTP/1.1"); - this.content(""); - } - - } - - /** - * Base class for table matchers. - * - * @param The concrete type of the matcher - */ - public static abstract class TableMatcher> - extends AbstractSnippetContentMatcher { - - protected TableMatcher(TemplateFormat templateFormat) { - super(templateFormat); - } - - public abstract T row(String... entries); - - public abstract T configuration(String configuration); - - } - - /** - * A {@link Matcher} for an Asciidoctor table. - */ - public static final class AsciidoctorTableMatcher - extends TableMatcher { - - private AsciidoctorTableMatcher(String title, String... columns) { - super(TemplateFormats.asciidoctor()); - if (StringUtils.hasText(title)) { - this.addLine("." + title); - } - this.addLine("|==="); - String header = "|" + StringUtils - .collectionToDelimitedString(Arrays.asList(columns), "|"); - this.addLine(header); - this.addLine(""); - this.addLine("|==="); - } - - @Override - public AsciidoctorTableMatcher row(String... entries) { - for (String entry : entries) { - this.addLine(-1, "|" + escapeEntry(entry)); - } - this.addLine(-1, ""); - return this; - } - - private String escapeEntry(String entry) { - if (entry.startsWith("`") && entry.endsWith("`")) { - return "`+" + entry.substring(1, entry.length() - 1) + "+`"; - } - return entry; - } - - @Override - public AsciidoctorTableMatcher configuration(String configuration) { - this.addLine(0, configuration); - return this; - } - - } - - /** - * A {@link Matcher} for a Markdown table. - */ - public static final class MarkdownTableMatcher - extends TableMatcher { - - private MarkdownTableMatcher(String title, String... columns) { - super(TemplateFormats.asciidoctor()); - if (StringUtils.hasText(title)) { - this.addLine(title); - this.addLine(""); - } - String header = StringUtils - .collectionToDelimitedString(Arrays.asList(columns), " | "); - this.addLine(header); - List components = new ArrayList<>(); - for (String column : columns) { - StringBuilder dashes = new StringBuilder(); - for (int i = 0; i < column.length(); i++) { - dashes.append("-"); - } - components.add(dashes.toString()); - } - this.addLine(StringUtils.collectionToDelimitedString(components, " | ")); - this.addLine(""); - } - - @Override - public MarkdownTableMatcher row(String... entries) { - this.addLine(-1, StringUtils - .collectionToDelimitedString(Arrays.asList(entries), " | ")); - return this; - } - - @Override - public MarkdownTableMatcher configuration(String configuration) { - throw new UnsupportedOperationException( - "Markdown does not support table configuration"); - } - - } - - /** - * A {@link Matcher} for a snippet file. - */ - public static final class SnippetMatcher extends BaseMatcher { - - private final TemplateFormat templateFormat; - - private Matcher expectedContents; - - private SnippetMatcher(TemplateFormat templateFormat) { - this.templateFormat = templateFormat; - } - - @Override - public boolean matches(Object item) { - if (snippetFileExists(item)) { - if (this.expectedContents != null) { - try { - return this.expectedContents.matches(read((File) item)); - } - catch (IOException e) { - return false; - } - } - return true; - } - return false; - } - - private boolean snippetFileExists(Object item) { - return item instanceof File && ((File) item).isFile(); - } - - private String read(File snippetFile) throws IOException { - return FileCopyUtils.copyToString( - new InputStreamReader(new FileInputStream(snippetFile), "UTF-8")); - } - - @Override - public void describeMismatch(Object item, Description description) { - if (!snippetFileExists(item)) { - description.appendText("The file " + item + " does not exist"); - } - else if (this.expectedContents != null) { - try { - this.expectedContents.describeMismatch(read((File) item), - description); - } - catch (IOException e) { - description - .appendText("The contents of " + item + " cound not be read"); - } - } - } - - @Override - public void describeTo(Description description) { - if (this.expectedContents != null) { - this.expectedContents.describeTo(description); - } - else { - description - .appendText(this.templateFormat.getFileExtension() + " snippet"); - } - } - - public SnippetMatcher withContents(Matcher matcher) { - this.expectedContents = matcher; - return this; - } - - } - -} diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java index c3b18f93..4328cfc4 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRequestConverterTests.java @@ -36,12 +36,7 @@ import org.springframework.restdocs.operation.RequestCookie; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -58,8 +53,8 @@ public class MockMvcRequestConverterTests { public void httpRequest() throws Exception { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.get("/foo")); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test @@ -68,26 +63,27 @@ public class MockMvcRequestConverterTests { .buildRequest(new MockServletContext()); mockRequest.setServerPort(8080); OperationRequest request = this.factory.convert(mockRequest); - assertThat(request.getUri(), is(URI.create("http://localhost:8080/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void requestWithContextPath() throws Exception { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.get("/foo/bar").contextPath("/foo")); - assertThat(request.getUri(), is(URI.create("http://localhost/foo/bar"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo/bar")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void requestWithHeaders() throws Exception { OperationRequest request = createOperationRequest(MockMvcRequestBuilders .get("/foo").header("a", "alpha", "apple").header("b", "bravo")); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); - assertThat(request.getHeaders(), hasEntry("a", Arrays.asList("alpha", "apple"))); - assertThat(request.getHeaders(), hasEntry("b", Arrays.asList("bravo"))); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(request.getHeaders()).containsEntry("a", + Arrays.asList("alpha", "apple")); + assertThat(request.getHeaders()).containsEntry("b", Arrays.asList("bravo")); } @Test @@ -96,19 +92,19 @@ public class MockMvcRequestConverterTests { MockMvcRequestBuilders.get("/foo").cookie( new javax.servlet.http.Cookie("cookieName1", "cookieVal1"), new javax.servlet.http.Cookie("cookieName2", "cookieVal2"))); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); - assertThat(request.getCookies().size(), is(equalTo(2))); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(request.getCookies().size()).isEqualTo(2); Iterator cookieIterator = request.getCookies().iterator(); RequestCookie cookie1 = cookieIterator.next(); - assertThat(cookie1.getName(), is(equalTo("cookieName1"))); - assertThat(cookie1.getValue(), is(equalTo("cookieVal1"))); + assertThat(cookie1.getName()).isEqualTo("cookieName1"); + assertThat(cookie1.getValue()).isEqualTo("cookieVal1"); RequestCookie cookie2 = cookieIterator.next(); - assertThat(cookie2.getName(), is(equalTo("cookieName2"))); - assertThat(cookie2.getValue(), is(equalTo("cookieVal2"))); + assertThat(cookie2.getName()).isEqualTo("cookieName2"); + assertThat(cookie2.getValue()).isEqualTo("cookieVal2"); } @Test @@ -118,8 +114,8 @@ public class MockMvcRequestConverterTests { mockRequest.setScheme("https"); mockRequest.setServerPort(443); OperationRequest request = this.factory.convert(mockRequest); - assertThat(request.getUri(), is(URI.create("https://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("https://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test @@ -129,45 +125,45 @@ public class MockMvcRequestConverterTests { mockRequest.setScheme("https"); mockRequest.setServerPort(8443); OperationRequest request = this.factory.convert(mockRequest); - assertThat(request.getUri(), is(URI.create("https://localhost:8443/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("https://localhost:8443/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void getRequestWithParametersProducesUriWithQueryString() throws Exception { OperationRequest request = createOperationRequest(MockMvcRequestBuilders .get("/foo").param("a", "alpha", "apple").param("b", "br&vo")); - assertThat(request.getUri(), - is(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo"))); - assertThat(request.getParameters().size(), is(2)); - assertThat(request.getParameters(), - hasEntry("a", Arrays.asList("alpha", "apple"))); - assertThat(request.getParameters(), hasEntry("b", Arrays.asList("br&vo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()) + .isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); + assertThat(request.getParameters().size()).isEqualTo(2); + assertThat(request.getParameters()).containsEntry("a", + Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void getRequestWithQueryStringPopulatesParameters() throws Exception { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.get("/foo?a=alpha&b=bravo")); - assertThat(request.getUri(), - is(URI.create("http://localhost/foo?a=alpha&b=bravo"))); - assertThat(request.getParameters().size(), is(2)); - assertThat(request.getParameters(), hasEntry("a", Arrays.asList("alpha"))); - assertThat(request.getParameters(), hasEntry("b", Arrays.asList("bravo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()) + .isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); + assertThat(request.getParameters().size()).isEqualTo(2); + assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha")); + assertThat(request.getParameters()).containsEntry("b", Arrays.asList("bravo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test public void postRequestWithParameters() throws Exception { OperationRequest request = createOperationRequest(MockMvcRequestBuilders .post("/foo").param("a", "alpha", "apple").param("b", "br&vo")); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); - assertThat(request.getParameters().size(), is(2)); - assertThat(request.getParameters(), - hasEntry("a", Arrays.asList("alpha", "apple"))); - assertThat(request.getParameters(), hasEntry("b", Arrays.asList("br&vo"))); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getParameters().size()).isEqualTo(2); + assertThat(request.getParameters()).containsEntry("a", + Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @Test @@ -175,15 +171,15 @@ public class MockMvcRequestConverterTests { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.multipart("/foo") .file(new MockMultipartFile("file", new byte[] { 1, 2, 3, 4 }))); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); - assertThat(request.getParts().size(), is(1)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getParts().size()).isEqualTo(1); OperationRequestPart part = request.getParts().iterator().next(); - assertThat(part.getName(), is(equalTo("file"))); - assertThat(part.getSubmittedFileName(), is(nullValue())); - assertThat(part.getHeaders().size(), is(1)); - assertThat(part.getHeaders().getContentLength(), is(4L)); - assertThat(part.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 }))); + assertThat(part.getName()).isEqualTo("file"); + assertThat(part.getSubmittedFileName()).isNull(); + assertThat(part.getHeaders().size()).isEqualTo(1); + assertThat(part.getHeaders().getContentLength()).isEqualTo(4L); + assertThat(part.getContent()).isEqualTo(new byte[] { 1, 2, 3, 4 }); } @Test @@ -191,14 +187,14 @@ public class MockMvcRequestConverterTests { OperationRequest request = createOperationRequest( MockMvcRequestBuilders.multipart("/foo").file(new MockMultipartFile( "file", "original", "image/png", new byte[] { 1, 2, 3, 4 }))); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); - assertThat(request.getParts().size(), is(1)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getParts().size()).isEqualTo(1); OperationRequestPart part = request.getParts().iterator().next(); - assertThat(part.getName(), is(equalTo("file"))); - assertThat(part.getSubmittedFileName(), is(equalTo("original"))); - assertThat(part.getHeaders().getContentType(), is(MediaType.IMAGE_PNG)); - assertThat(part.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 }))); + assertThat(part.getName()).isEqualTo("file"); + assertThat(part.getSubmittedFileName()).isEqualTo("original"); + assertThat(part.getHeaders().getContentType()).isEqualTo(MediaType.IMAGE_PNG); + assertThat(part.getContent()).isEqualTo(new byte[] { 1, 2, 3, 4 }); } @Test @@ -215,14 +211,14 @@ public class MockMvcRequestConverterTests { given(mockPart.getSubmittedFileName()).willReturn("submitted.txt"); mockRequest.addPart(mockPart); OperationRequest request = this.factory.convert(mockRequest); - assertThat(request.getParts().size(), is(1)); + assertThat(request.getParts().size()).isEqualTo(1); OperationRequestPart part = request.getParts().iterator().next(); - assertThat(part.getName(), is(equalTo("part-name"))); - assertThat(part.getSubmittedFileName(), is(equalTo("submitted.txt"))); - assertThat(part.getHeaders().getContentType(), is(nullValue())); - assertThat(part.getHeaders().get("a"), contains("alpha")); - assertThat(part.getHeaders().get("b"), contains("bravo", "banana")); - assertThat(part.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 }))); + assertThat(part.getName()).isEqualTo("part-name"); + assertThat(part.getSubmittedFileName()).isEqualTo("submitted.txt"); + assertThat(part.getHeaders().getContentType()).isNull(); + assertThat(part.getHeaders().get("a")).containsExactly("alpha"); + assertThat(part.getHeaders().get("b")).containsExactly("bravo", "banana"); + assertThat(part.getContent()).isEqualTo(new byte[] { 1, 2, 3, 4 }); } @Test @@ -240,14 +236,14 @@ public class MockMvcRequestConverterTests { given(mockPart.getContentType()).willReturn("image/png"); mockRequest.addPart(mockPart); OperationRequest request = this.factory.convert(mockRequest); - assertThat(request.getParts().size(), is(1)); + assertThat(request.getParts().size()).isEqualTo(1); OperationRequestPart part = request.getParts().iterator().next(); - assertThat(part.getName(), is(equalTo("part-name"))); - assertThat(part.getSubmittedFileName(), is(equalTo("submitted.png"))); - assertThat(part.getHeaders().getContentType(), is(MediaType.IMAGE_PNG)); - assertThat(part.getHeaders().get("a"), contains("alpha")); - assertThat(part.getHeaders().get("b"), contains("bravo", "banana")); - assertThat(part.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 }))); + assertThat(part.getName()).isEqualTo("part-name"); + assertThat(part.getSubmittedFileName()).isEqualTo("submitted.png"); + assertThat(part.getHeaders().getContentType()).isEqualTo(MediaType.IMAGE_PNG); + assertThat(part.getHeaders().get("a")).containsExactly("alpha"); + assertThat(part.getHeaders().get("b")).containsExactly("bravo", "banana"); + assertThat(part.getContent()).isEqualTo(new byte[] { 1, 2, 3, 4 }); } private OperationRequest createOperationRequest(MockHttpServletRequestBuilder builder) diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverterTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverterTests.java index b34ffe34..48df98c3 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverterTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcResponseConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,10 +28,7 @@ import org.springframework.http.HttpStatus; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.restdocs.operation.OperationResponse; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MockMvcResponseConverter}. @@ -46,29 +43,22 @@ public class MockMvcResponseConverterTests { public void basicResponse() { MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(HttpServletResponse.SC_OK); - OperationResponse operationResponse = this.factory.convert(response); - - assertThat(operationResponse.getStatus(), is(HttpStatus.OK)); + assertThat(operationResponse.getStatus()).isEqualTo(HttpStatus.OK); } @Test public void responseWithCookie() { MockHttpServletResponse response = new MockHttpServletResponse(); response.setStatus(HttpServletResponse.SC_OK); - Cookie cookie = new Cookie("name", "value"); cookie.setDomain("localhost"); cookie.setHttpOnly(true); - response.addCookie(cookie); - OperationResponse operationResponse = this.factory.convert(response); - - assertThat(operationResponse.getHeaders().size(), is(1)); - assertTrue(operationResponse.getHeaders().containsKey(HttpHeaders.SET_COOKIE)); - assertThat(operationResponse.getHeaders().get(HttpHeaders.SET_COOKIE), equalTo( - Collections.singletonList("name=value; Domain=localhost; HttpOnly"))); + assertThat(operationResponse.getHeaders()).hasSize(1); + assertThat(operationResponse.getHeaders()).containsEntry(HttpHeaders.SET_COOKIE, + Collections.singletonList("name=value; Domain=localhost; HttpOnly")); } } diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java index 0377ec0b..4cfac702 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,10 +28,7 @@ import org.springframework.test.web.servlet.request.RequestPostProcessor; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link MockMvcRestDocumentationConfigurer}. @@ -51,7 +48,6 @@ public class MockMvcRestDocumentationConfigurerTests { RequestPostProcessor postProcessor = new MockMvcRestDocumentationConfigurer( this.restDocumentation).beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); - assertUriConfiguration("http", "localhost", 8080); } @@ -61,7 +57,6 @@ public class MockMvcRestDocumentationConfigurerTests { this.restDocumentation).uris().withScheme("https") .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); - assertUriConfiguration("https", "localhost", 8080); } @@ -71,7 +66,6 @@ public class MockMvcRestDocumentationConfigurerTests { this.restDocumentation).uris().withHost("api.example.com") .beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); - assertUriConfiguration("http", "api.example.com", 8080); } @@ -81,7 +75,6 @@ public class MockMvcRestDocumentationConfigurerTests { this.restDocumentation).uris().withPort(8081).beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); - assertUriConfiguration("http", "localhost", 8081); } @@ -91,20 +84,20 @@ public class MockMvcRestDocumentationConfigurerTests { this.restDocumentation).uris().withPort(8081).beforeMockMvcCreated(null, null); postProcessor.postProcessRequest(this.request); - assertThat(this.request.getHeader("Content-Length"), is(nullValue())); + assertThat(this.request.getHeader("Content-Length")).isNull(); } private void assertUriConfiguration(String scheme, String host, int port) { - assertEquals(scheme, this.request.getScheme()); - assertEquals(host, this.request.getServerName()); - assertEquals(port, this.request.getServerPort()); + assertThat(scheme).isEqualTo(this.request.getScheme()); + assertThat(host).isEqualTo(this.request.getServerName()); + assertThat(port).isEqualTo(this.request.getServerPort()); RequestContextHolder .setRequestAttributes(new ServletRequestAttributes(this.request)); try { URI uri = BasicLinkBuilder.linkToCurrentMapping().toUri(); - assertEquals(scheme, uri.getScheme()); - assertEquals(host, uri.getHost()); - assertEquals(port, uri.getPort()); + assertThat(scheme).isEqualTo(uri.getScheme()); + assertThat(host).isEqualTo(uri.getHost()); + assertThat(port).isEqualTo(uri.getPort()); } finally { RequestContextHolder.resetRequestAttributes(); diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java index 434d586e..b3dabe3a 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/MockMvcRestDocumentationIntegrationTests.java @@ -17,8 +17,12 @@ package org.springframework.restdocs.mockmvc; import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; import java.net.URL; import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -28,6 +32,7 @@ import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; +import org.assertj.core.api.Condition; import org.junit.After; import org.junit.Before; import org.junit.Rule; @@ -43,13 +48,14 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.restdocs.JUnitRestDocumentation; import org.springframework.restdocs.mockmvc.MockMvcRestDocumentationIntegrationTests.TestConfiguration; -import org.springframework.restdocs.test.SnippetMatchers.HttpRequestMatcher; +import org.springframework.restdocs.test.SnippetConditions.HttpRequestCondition; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.util.FileCopyUtils; import org.springframework.util.FileSystemUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -57,11 +63,8 @@ import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.springframework.restdocs.cli.CliDocumentation.curlRequest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; @@ -85,14 +88,11 @@ import static org.springframework.restdocs.request.RequestDocumentation.partWith import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParts; -import static org.springframework.restdocs.snippet.Attributes.attributes; -import static org.springframework.restdocs.snippet.Attributes.key; import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor; import static org.springframework.restdocs.templates.TemplateFormats.markdown; -import static org.springframework.restdocs.test.SnippetMatchers.codeBlock; -import static org.springframework.restdocs.test.SnippetMatchers.httpRequest; -import static org.springframework.restdocs.test.SnippetMatchers.httpResponse; -import static org.springframework.restdocs.test.SnippetMatchers.snippet; +import static org.springframework.restdocs.test.SnippetConditions.codeBlock; +import static org.springframework.restdocs.test.SnippetConditions.httpRequest; +import static org.springframework.restdocs.test.SnippetConditions.httpResponse; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -132,7 +132,6 @@ public class MockMvcRestDocumentationIntegrationTests { .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation) .snippets().withEncoding("UTF-8")) .build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("basic")); assertExpectedSnippetFilesExist(new File("build/generated-snippets/basic"), @@ -145,7 +144,6 @@ public class MockMvcRestDocumentationIntegrationTests { .apply(new MockMvcRestDocumentationConfigurer(this.restDocumentation) .snippets().withEncoding("UTF-8").withTemplateFormat(markdown())) .build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("basic-markdown")); assertExpectedSnippetFilesExist( @@ -157,33 +155,29 @@ public class MockMvcRestDocumentationIntegrationTests { public void curlSnippetWithContent() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(post("/").accept(MediaType.APPLICATION_JSON).content("content")) .andExpect(status().isOk()).andDo(document("curl-snippet-with-content")); assertThat(new File( - "build/generated-snippets/curl-snippet-with-content/curl-request.adoc"), - is(snippet(asciidoctor()) - .withContents(codeBlock(asciidoctor(), "bash").content(String + "build/generated-snippets/curl-snippet-with-content/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent(String .format("$ curl 'http://localhost:8080/' -i -X POST \\%n" + " -H 'Accept: application/json' \\%n" - + " -d 'content'"))))); + + " -d 'content'")))); } @Test public void curlSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON) .cookie(new Cookie("cookieName", "cookieVal"))).andExpect(status().isOk()) .andDo(document("curl-snippet-with-cookies")); assertThat(new File( - "build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc"), - is(snippet(asciidoctor()) - .withContents(codeBlock(asciidoctor(), "bash").content(String + "build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent(String .format("$ curl 'http://localhost:8080/' -i -X GET \\%n" + " -H 'Accept: application/json' \\%n" - + " --cookie 'cookieName=cookieVal'"))))); + + " --cookie 'cookieName=cookieVal'")))); } @Test @@ -194,12 +188,12 @@ public class MockMvcRestDocumentationIntegrationTests { .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andDo(document("curl-snippet-with-query-string")); assertThat(new File( - "build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc"), - is(snippet(asciidoctor()).withContents( - codeBlock(asciidoctor(), "bash").content(String.format("$ curl " - + "'http://localhost:8080/?foo=bar' -i -X POST \\%n" - + " -H 'Accept: application/json' \\%n" - + " -d 'a=alpha'"))))); + "build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash") + .withContent(String.format("$ curl " + + "'http://localhost:8080/?foo=bar' -i -X POST \\%n" + + " -H 'Accept: application/json' \\%n" + + " -d 'a=alpha'")))); } @Test @@ -210,44 +204,41 @@ public class MockMvcRestDocumentationIntegrationTests { .content("some content")).andExpect(status().isOk()) .andDo(document("curl-snippet-with-content-and-parameters")); assertThat(new File( - "build/generated-snippets/curl-snippet-with-content-and-parameters/curl-request.adoc"), - is(snippet(asciidoctor()).withContents( - codeBlock(asciidoctor(), "bash").content(String.format( - "$ curl 'http://localhost:8080/?a=alpha' -i -X POST \\%n" + "build/generated-snippets/curl-snippet-with-content-and-parameters/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent(String + .format("$ curl 'http://localhost:8080/?a=alpha' -i -X POST \\%n" + " -H 'Accept: application/json' \\%n" - + " -d 'some content'"))))); + + " -d 'some content'")))); } @Test public void httpieSnippetWithContent() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(post("/").accept(MediaType.APPLICATION_JSON).content("content")) .andExpect(status().isOk()) .andDo(document("httpie-snippet-with-content")); assertThat(new File( - "build/generated-snippets/httpie-snippet-with-content/httpie-request.adoc"), - is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") - .content(String.format("$ echo 'content' | " - + "http POST 'http://localhost:8080/' \\%n" - + " 'Accept:application/json'"))))); + "build/generated-snippets/httpie-snippet-with-content/httpie-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash") + .withContent(String.format("$ echo 'content' | " + + "http POST 'http://localhost:8080/' \\%n" + + " 'Accept:application/json'")))); } @Test public void httpieSnippetWithCookies() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON) .cookie(new Cookie("cookieName", "cookieVal"))).andExpect(status().isOk()) .andDo(document("httpie-snippet-with-cookies")); assertThat(new File( - "build/generated-snippets/httpie-snippet-with-cookies/httpie-request.adoc"), - is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") - .content(String.format("$ http GET 'http://localhost:8080/' \\%n" - + " 'Accept:application/json' \\%n" - + " 'Cookie:cookieName=cookieVal'"))))); + "build/generated-snippets/httpie-snippet-with-cookies/httpie-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent( + String.format("$ http GET 'http://localhost:8080/' \\%n" + + " 'Accept:application/json' \\%n" + + " 'Cookie:cookieName=cookieVal'")))); } @Test @@ -258,11 +249,11 @@ public class MockMvcRestDocumentationIntegrationTests { .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andDo(document("httpie-snippet-with-query-string")); assertThat(new File( - "build/generated-snippets/httpie-snippet-with-query-string/httpie-request.adoc"), - is(snippet(asciidoctor()).withContents( - codeBlock(asciidoctor(), "bash").content(String.format("$ http " - + "--form POST 'http://localhost:8080/?foo=bar' \\%n" - + " 'Accept:application/json' \\%n 'a=alpha'"))))); + "build/generated-snippets/httpie-snippet-with-query-string/httpie-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash") + .withContent(String.format("$ http " + + "--form POST 'http://localhost:8080/?foo=bar' \\%n" + + " 'Accept:application/json' \\%n 'a=alpha'")))); } @Test @@ -273,18 +264,17 @@ public class MockMvcRestDocumentationIntegrationTests { .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andDo(document("httpie-snippet-post-with-content-and-parameters")); assertThat(new File( - "build/generated-snippets/httpie-snippet-post-with-content-and-parameters/httpie-request.adoc"), - is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") - .content(String.format("$ echo " + "'some content' | http POST " - + "'http://localhost:8080/?a=alpha' \\%n" - + " 'Accept:application/json'"))))); + "build/generated-snippets/httpie-snippet-post-with-content-and-parameters/httpie-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent( + String.format("$ echo " + "'some content' | http POST " + + "'http://localhost:8080/?a=alpha' \\%n" + + " 'Accept:application/json'")))); } @Test public void linksSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("links", links(linkWithRel("rel").description("The description")))); @@ -298,11 +288,9 @@ public class MockMvcRestDocumentationIntegrationTests { public void pathParametersSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("{foo}", "/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("links", pathParameters( parameterWithName("foo").description("The description")))); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "path-parameters.adoc"); @@ -312,11 +300,9 @@ public class MockMvcRestDocumentationIntegrationTests { public void requestParametersSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").param("foo", "bar").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("links", requestParameters( parameterWithName("foo").description("The description")))); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-parameters.adoc"); @@ -326,12 +312,10 @@ public class MockMvcRestDocumentationIntegrationTests { public void requestFieldsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").param("foo", "bar").content("{\"a\":\"alpha\"}") .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andDo(document("links", requestFields( fieldWithPath("a").description("The description")))); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-fields.adoc"); @@ -341,11 +325,9 @@ public class MockMvcRestDocumentationIntegrationTests { public void requestPartsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(multipart("/upload").file("foo", "bar".getBytes())) .andExpect(status().isOk()).andDo(document("request-parts", requestParts( partWithName("foo").description("The description")))); - assertExpectedSnippetFilesExist( new File("build/generated-snippets/request-parts"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "request-parts.adoc"); @@ -355,14 +337,12 @@ public class MockMvcRestDocumentationIntegrationTests { public void responseFieldsSnippet() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").param("foo", "bar").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("links", responseFields(fieldWithPath("a").description("The description"), subsectionWithPath("links") .description("Links to other resources")))); - assertExpectedSnippetFilesExist(new File("build/generated-snippets/links"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "response-fields.adoc"); @@ -372,24 +352,20 @@ public class MockMvcRestDocumentationIntegrationTests { public void responseWithSetCookie() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/set-cookie")).andExpect(status().isOk()) .andDo(document("set-cookie", responseHeaders(headerWithName(HttpHeaders.SET_COOKIE) .description("set-cookie")))); - - assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc"), - is(snippet(asciidoctor()) - .withContents(httpResponse(asciidoctor(), HttpStatus.OK).header( - HttpHeaders.SET_COOKIE, - "name=value; Domain=localhost; HttpOnly")))); + assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc")) + .has(content(httpResponse(asciidoctor(), HttpStatus.OK).header( + HttpHeaders.SET_COOKIE, + "name=value; Domain=localhost; HttpOnly"))); } @Test public void parameterizedOutputDirectory() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("{method-name}")); assertExpectedSnippetFilesExist( @@ -402,13 +378,11 @@ public class MockMvcRestDocumentationIntegrationTests { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .alwaysDo(document("{method-name}-{step}")).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertExpectedSnippetFilesExist( new File("build/generated-snippets/multi-step-1/"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertExpectedSnippetFilesExist( @@ -428,11 +402,9 @@ public class MockMvcRestDocumentationIntegrationTests { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .alwaysDo(documentation).build(); - mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(documentation.document( responseHeaders(headerWithName("a").description("one")))); - assertExpectedSnippetFilesExist( new File( "build/generated-snippets/always-do-with-additional-snippets-1/"), @@ -444,9 +416,7 @@ public class MockMvcRestDocumentationIntegrationTests { public void preprocessedRequest() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - Pattern pattern = Pattern.compile("(\"alpha\")"); - MvcResult result = mockMvc .perform(get("/").header("a", "alpha").header("b", "bravo") .contentType(MediaType.APPLICATION_JSON) @@ -458,18 +428,17 @@ public class MockMvcRestDocumentationIntegrationTests { HttpHeaders.CONTENT_LENGTH), replacePattern(pattern, "\"<>\"")))) .andReturn(); - - HttpRequestMatcher originalRequest = httpRequest(asciidoctor(), RequestMethod.GET, - "/"); + HttpRequestCondition originalRequest = httpRequest(asciidoctor(), + RequestMethod.GET, "/"); for (String headerName : iterable(result.getRequest().getHeaderNames())) { originalRequest.header(headerName, result.getRequest().getHeader(headerName)); } assertThat( - new File("build/generated-snippets/original-request/http-request.adoc"), - is(snippet(asciidoctor()).withContents(originalRequest - .header("Host", "localhost:8080").header("Content-Length", "13") - .content("{\"a\":\"alpha\"}")))); - HttpRequestMatcher preprocessedRequest = httpRequest(asciidoctor(), + new File("build/generated-snippets/original-request/http-request.adoc")) + .has(content(originalRequest.header("Host", "localhost:8080") + .header("Content-Length", "13") + .content("{\"a\":\"alpha\"}"))); + HttpRequestCondition preprocessedRequest = httpRequest(asciidoctor(), RequestMethod.GET, "/"); List removedHeaders = Arrays.asList("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); @@ -481,9 +450,8 @@ public class MockMvcRestDocumentationIntegrationTests { } String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); assertThat(new File( - "build/generated-snippets/preprocessed-request/http-request.adoc"), - is(snippet(asciidoctor()) - .withContents(preprocessedRequest.content(prettyPrinted)))); + "build/generated-snippets/preprocessed-request/http-request.adoc")) + .has(content(preprocessedRequest.content(prettyPrinted))); } @Test @@ -503,7 +471,7 @@ public class MockMvcRestDocumentationIntegrationTests { .accept(MediaType.APPLICATION_JSON).content("{\"a\":\"alpha\"}")) .andDo(document("default-preprocessed-request")).andReturn(); - HttpRequestMatcher preprocessedRequest = httpRequest(asciidoctor(), + HttpRequestCondition preprocessedRequest = httpRequest(asciidoctor(), RequestMethod.GET, "/"); List removedHeaders = Arrays.asList("a", HttpHeaders.HOST, HttpHeaders.CONTENT_LENGTH); @@ -515,9 +483,8 @@ public class MockMvcRestDocumentationIntegrationTests { } String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); assertThat(new File( - "build/generated-snippets/default-preprocessed-request/http-request.adoc"), - is(snippet(asciidoctor()) - .withContents(preprocessedRequest.content(prettyPrinted)))); + "build/generated-snippets/default-preprocessed-request/http-request.adoc")) + .has(content(preprocessedRequest.content(prettyPrinted))); } @Test @@ -536,23 +503,22 @@ public class MockMvcRestDocumentationIntegrationTests { String original = "{\"a\":\"alpha\",\"links\":[{\"rel\":\"rel\"," + "\"href\":\"href\"}]}"; assertThat( - new File("build/generated-snippets/original-response/http-response.adoc"), - is(snippet(asciidoctor()).withContents( - httpResponse(asciidoctor(), HttpStatus.OK).header("a", "alpha") + new File("build/generated-snippets/original-response/http-response.adoc")) + .has(content(httpResponse(asciidoctor(), HttpStatus.OK) + .header("a", "alpha") .header("Content-Type", "application/json;charset=UTF-8") .header(HttpHeaders.CONTENT_LENGTH, original.getBytes().length) - .content(original)))); + .content(original))); String prettyPrinted = String.format("{%n \"a\" : \"<>\",%n \"links\" : " + "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}"); assertThat(new File( - "build/generated-snippets/preprocessed-response/http-response.adoc"), - is(snippet(asciidoctor()) - .withContents(httpResponse(asciidoctor(), HttpStatus.OK) + "build/generated-snippets/preprocessed-response/http-response.adoc")) + .has(content(httpResponse(asciidoctor(), HttpStatus.OK) .header("Content-Type", "application/json;charset=UTF-8") .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) - .content(prettyPrinted)))); + .content(prettyPrinted))); } @Test @@ -572,20 +538,18 @@ public class MockMvcRestDocumentationIntegrationTests { String prettyPrinted = String.format("{%n \"a\" : \"<>\",%n \"links\" : " + "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}"); assertThat(new File( - "build/generated-snippets/default-preprocessed-response/http-response.adoc"), - is(snippet(asciidoctor()) - .withContents(httpResponse(asciidoctor(), HttpStatus.OK) + "build/generated-snippets/default-preprocessed-response/http-response.adoc")) + .has(content(httpResponse(asciidoctor(), HttpStatus.OK) .header("Content-Type", "application/json;charset=UTF-8") .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) - .content(prettyPrinted)))); + .content(prettyPrinted))); } @Test public void customSnippetTemplate() throws Exception { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)).build(); - ClassLoader classLoader = new URLClassLoader(new URL[] { new File("src/test/resources/custom-snippet-templates").toURI().toURL() }, getClass().getClassLoader()); @@ -600,11 +564,8 @@ public class MockMvcRestDocumentationIntegrationTests { Thread.currentThread().setContextClassLoader(previous); } assertThat(new File( - "build/generated-snippets/custom-snippet-template/curl-request.adoc"), - is(snippet(asciidoctor()).withContents(equalTo("Custom curl request")))); - - mockMvc.perform(get("/")).andDo(document("index", curlRequest( - attributes(key("title").value("Access the index using curl"))))); + "build/generated-snippets/custom-snippet-template/curl-request.adoc")) + .hasContent("Custom curl request"); } @Test @@ -615,13 +576,11 @@ public class MockMvcRestDocumentationIntegrationTests { mockMvc.perform( get("/custom/").contextPath("/custom").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andDo(document("custom-context-path")); - assertThat( - new File( - "build/generated-snippets/custom-context-path/curl-request.adoc"), - is(snippet(asciidoctor()).withContents( - codeBlock(asciidoctor(), "bash").content(String.format( - "$ curl 'http://localhost:8080/custom/' -i -X GET \\%n" - + " -H 'Accept: application/json'"))))); + assertThat(new File( + "build/generated-snippets/custom-context-path/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent(String + .format("$ curl 'http://localhost:8080/custom/' -i -X GET \\%n" + + " -H 'Accept: application/json'")))); } @Test @@ -635,10 +594,29 @@ public class MockMvcRestDocumentationIntegrationTests { private void assertExpectedSnippetFilesExist(File directory, String... snippets) { for (String snippet : snippets) { - assertTrue(new File(directory, snippet).isFile()); + assertThat(new File(directory, snippet)).isFile(); } } + private Condition content(final Condition delegate) { + return new Condition() { + + @Override + public boolean matches(File value) { + try { + return delegate + .matches(FileCopyUtils.copyToString(new InputStreamReader( + new FileInputStream(value), StandardCharsets.UTF_8))); + } + catch (IOException ex) { + fail("Failed to read '" + value + "'", ex); + return false; + } + } + + }; + } + /** * Test configuration that enables Spring MVC. */ diff --git a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java index ee90dfb3..5f1f5770 100644 --- a/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java +++ b/spring-restdocs-mockmvc/src/test/java/org/springframework/restdocs/mockmvc/RestDocumentationRequestBuildersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,9 +28,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.restdocs.generate.RestDocumentationGenerator; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.fileUpload; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; @@ -144,18 +142,17 @@ public class RestDocumentationRequestBuildersTests { private void assertTemplate(MockHttpServletRequestBuilder builder, HttpMethod httpMethod) { MockHttpServletRequest request = builder.buildRequest(this.servletContext); - assertThat( - (String) request.getAttribute( - RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE), - is(equalTo("{template}"))); - assertThat(request.getRequestURI(), is(equalTo("t"))); - assertThat(request.getMethod(), is(equalTo(httpMethod.name()))); + assertThat((String) request + .getAttribute(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE)) + .isEqualTo("{template}"); + assertThat(request.getRequestURI()).isEqualTo("t"); + assertThat(request.getMethod()).isEqualTo(httpMethod.name()); } private void assertUri(MockHttpServletRequestBuilder builder, HttpMethod httpMethod) { MockHttpServletRequest request = builder.buildRequest(this.servletContext); - assertThat(request.getRequestURI(), is(equalTo("/uri"))); - assertThat(request.getMethod(), is(equalTo(httpMethod.name()))); + assertThat(request.getRequestURI()).isEqualTo("/uri"); + assertThat(request.getMethod()).isEqualTo(httpMethod.name()); } } diff --git a/spring-restdocs-restassured/build.gradle b/spring-restdocs-restassured/build.gradle index 6e042f32..53433def 100644 --- a/spring-restdocs-restassured/build.gradle +++ b/spring-restdocs-restassured/build.gradle @@ -5,8 +5,9 @@ dependencies { compile 'io.rest-assured:rest-assured' testCompile 'org.apache.tomcat.embed:tomcat-embed-core:8.5.13' - testCompile 'org.mockito:mockito-core' + testCompile 'org.assertj:assertj-core' testCompile 'org.hamcrest:hamcrest-library' + testCompile 'org.mockito:mockito-core' testCompile project(path: ':spring-restdocs-core', configuration: 'testArtifacts') } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java index ed239f3e..35ebe519 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRequestConverterTests.java @@ -23,6 +23,7 @@ import java.io.FileNotFoundException; import java.net.URI; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import io.restassured.RestAssured; @@ -33,15 +34,14 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.restdocs.operation.OperationRequest; import org.springframework.restdocs.operation.OperationRequestPart; import org.springframework.restdocs.operation.RequestCookie; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link RestAssuredRequestConverter}. @@ -64,8 +64,8 @@ public class RestAssuredRequestConverterTests { requestSpec.get("/foo/bar"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getUri(), is(equalTo( - URI.create("http://localhost:" + tomcat.getPort() + "/foo/bar")))); + assertThat(request.getUri()).isEqualTo( + URI.create("http://localhost:" + tomcat.getPort() + "/foo/bar")); } @Test @@ -74,7 +74,7 @@ public class RestAssuredRequestConverterTests { requestSpec.head("/foo/bar"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getMethod(), is(equalTo(HttpMethod.HEAD))); + assertThat(request.getMethod()).isEqualTo(HttpMethod.HEAD); } @Test @@ -84,8 +84,9 @@ public class RestAssuredRequestConverterTests { requestSpec.get("/"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParameters().size(), is(1)); - assertThat(request.getParameters().get("foo"), is(equalTo(Arrays.asList("bar")))); + assertThat(request.getParameters()).hasSize(1); + assertThat(request.getParameters()).containsEntry("foo", + Collections.singletonList("bar")); } @Test @@ -94,9 +95,9 @@ public class RestAssuredRequestConverterTests { requestSpec.get("/?foo=bar&foo=qix"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParameters().size(), is(1)); - assertThat(request.getParameters().get("foo"), - is(equalTo(Arrays.asList("bar", "qix")))); + assertThat(request.getParameters()).hasSize(1); + assertThat(request.getParameters()).containsEntry("foo", + Arrays.asList("bar", "qix")); } @Test @@ -106,8 +107,9 @@ public class RestAssuredRequestConverterTests { requestSpec.get("/"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParameters().size(), is(1)); - assertThat(request.getParameters().get("foo"), is(equalTo(Arrays.asList("bar")))); + assertThat(request.getParameters()).hasSize(1); + assertThat(request.getParameters()).containsEntry("foo", + Collections.singletonList("bar")); } @Test @@ -117,8 +119,9 @@ public class RestAssuredRequestConverterTests { requestSpec.get("/"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParameters().size(), is(1)); - assertThat(request.getParameters().get("foo"), is(equalTo(Arrays.asList("bar")))); + assertThat(request.getParameters()).hasSize(1); + assertThat(request.getParameters()).containsEntry("foo", + Collections.singletonList("bar")); } @Test @@ -128,10 +131,11 @@ public class RestAssuredRequestConverterTests { requestSpec.get("/"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getHeaders().toString(), request.getHeaders().size(), is(2)); - assertThat(request.getHeaders().get("Foo"), is(equalTo(Arrays.asList("bar")))); - assertThat(request.getHeaders().get("Host"), - is(equalTo(Arrays.asList("localhost:" + tomcat.getPort())))); + assertThat(request.getHeaders()).hasSize(2); + assertThat(request.getHeaders()).containsEntry("Foo", + Collections.singletonList("bar")); + assertThat(request.getHeaders()).containsEntry("Host", + Collections.singletonList("localhost:" + tomcat.getPort())); } @Test @@ -141,12 +145,13 @@ public class RestAssuredRequestConverterTests { requestSpec.get("/"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getHeaders().toString(), request.getHeaders().size(), is(3)); - assertThat(request.getHeaders().get("Foo"), is(equalTo(Arrays.asList("bar")))); - assertThat(request.getHeaders().get("Accept"), - is(equalTo(Arrays.asList("application/json")))); - assertThat(request.getHeaders().get("Host"), - is(equalTo(Arrays.asList("localhost:" + tomcat.getPort())))); + assertThat(request.getHeaders()).hasSize(3); + assertThat(request.getHeaders()).containsEntry("Foo", + Collections.singletonList("bar")); + assertThat(request.getHeaders()).containsEntry("Accept", + Collections.singletonList("application/json")); + assertThat(request.getHeaders()).containsEntry("Host", + Collections.singletonList("localhost:" + tomcat.getPort())); } @Test @@ -156,17 +161,17 @@ public class RestAssuredRequestConverterTests { requestSpec.get("/"); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getCookies().size(), is(equalTo(2))); + assertThat(request.getCookies().size()).isEqualTo(2); Iterator cookieIterator = request.getCookies().iterator(); RequestCookie cookie1 = cookieIterator.next(); - assertThat(cookie1.getName(), is(equalTo("cookie1"))); - assertThat(cookie1.getValue(), is(equalTo("cookieVal1"))); + assertThat(cookie1.getName()).isEqualTo("cookie1"); + assertThat(cookie1.getValue()).isEqualTo("cookieVal1"); RequestCookie cookie2 = cookieIterator.next(); - assertThat(cookie2.getName(), is(equalTo("cookie2"))); - assertThat(cookie2.getValue(), is(equalTo("cookieVal2"))); + assertThat(cookie2.getName()).isEqualTo("cookie2"); + assertThat(cookie2.getValue()).isEqualTo("cookieVal2"); } @Test @@ -178,19 +183,15 @@ public class RestAssuredRequestConverterTests { OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); Collection parts = request.getParts(); - assertThat(parts.size(), is(2)); - Iterator iterator = parts.iterator(); - OperationRequestPart part = iterator.next(); - assertThat(part.getName(), is(equalTo("a"))); - assertThat(part.getSubmittedFileName(), is(equalTo("a.txt"))); - assertThat(part.getContentAsString(), is(equalTo("alpha"))); - assertThat(part.getHeaders().getContentType(), is(equalTo(MediaType.TEXT_PLAIN))); - part = iterator.next(); - assertThat(part.getName(), is(equalTo("b"))); - assertThat(part.getSubmittedFileName(), is(equalTo("file"))); - assertThat(part.getContentAsString(), is(equalTo("{\"foo\":\"bar\"}"))); - assertThat(part.getHeaders().getContentType(), - is(equalTo(MediaType.APPLICATION_JSON))); + assertThat(parts).hasSize(2); + assertThat(parts).extracting("name").containsExactly("a", "b"); + assertThat(parts).extracting("submittedFileName").containsExactly("a.txt", + "file"); + assertThat(parts).extracting("contentAsString").containsExactly("alpha", + "{\"foo\":\"bar\"}"); + assertThat(parts).extracting("headers").extracting(HttpHeaders.CONTENT_TYPE) + .containsExactly(Collections.singletonList(MediaType.TEXT_PLAIN_VALUE), + Collections.singletonList(MediaType.APPLICATION_JSON_VALUE)); } @Test @@ -208,7 +209,7 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getContentAsString(), is(equalTo("body"))); + assertThat(request.getContentAsString()).isEqualTo("body"); } @Test @@ -218,7 +219,7 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getContentAsString(), is(equalTo("{\"foo\":\"bar\"}"))); + assertThat(request.getContentAsString()).isEqualTo("{\"foo\":\"bar\"}"); } @Test @@ -229,7 +230,7 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 }))); + assertThat(request.getContent()).isEqualTo(new byte[] { 1, 2, 3, 4 }); } @Test @@ -239,7 +240,7 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getContentAsString(), is(equalTo("file"))); + assertThat(request.getContentAsString()).isEqualTo("file"); } @Test @@ -261,8 +262,8 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParts().iterator().next().getContentAsString(), - is(equalTo("foo"))); + assertThat(request.getParts().iterator().next().getContentAsString()) + .isEqualTo("foo"); } @Test @@ -272,8 +273,8 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParts().iterator().next().getContentAsString(), - is(equalTo("foo"))); + assertThat(request.getParts().iterator().next().getContentAsString()) + .isEqualTo("foo"); } @Test @@ -283,8 +284,8 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParts().iterator().next().getContentAsString(), - is(equalTo("foo"))); + assertThat(request.getParts().iterator().next().getContentAsString()) + .isEqualTo("foo"); } @Test @@ -294,8 +295,8 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParts().iterator().next().getContentAsString(), - is(equalTo("file"))); + assertThat(request.getParts().iterator().next().getContentAsString()) + .isEqualTo("file"); } @Test @@ -317,8 +318,8 @@ public class RestAssuredRequestConverterTests { requestSpec.post(); OperationRequest request = this.factory .convert((FilterableRequestSpecification) requestSpec); - assertThat(request.getParts().iterator().next().getContentAsString(), - is(equalTo("{\"foo\":\"bar\"}"))); + assertThat(request.getParts().iterator().next().getContentAsString()) + .isEqualTo("{\"foo\":\"bar\"}"); } /** diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java index d15868d5..767c2526 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationConfigurerTests.java @@ -34,10 +34,7 @@ import org.springframework.restdocs.operation.preprocess.Preprocessors; import org.springframework.restdocs.snippet.WriterResolver; import org.springframework.restdocs.templates.TemplateEngine; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -83,20 +80,19 @@ public class RestAssuredRestDocumentationConfigurerTests { configurationCaptor.capture()); @SuppressWarnings("unchecked") Map configuration = configurationCaptor.getValue(); - assertThat(configuration, hasEntry(equalTo(TemplateEngine.class.getName()), - instanceOf(TemplateEngine.class))); - assertThat(configuration, hasEntry(equalTo(WriterResolver.class.getName()), - instanceOf(WriterResolver.class))); - assertThat(configuration, - hasEntry(equalTo( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS), - instanceOf(List.class))); - assertThat(configuration, hasEntry(equalTo( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR), - instanceOf(OperationRequestPreprocessor.class))); - assertThat(configuration, hasEntry(equalTo( - RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR), - instanceOf(OperationResponsePreprocessor.class))); + assertThat(configuration.get(TemplateEngine.class.getName())) + .isInstanceOf(TemplateEngine.class); + assertThat(configuration.get(WriterResolver.class.getName())) + .isInstanceOf(WriterResolver.class); + assertThat(configuration + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_SNIPPETS)) + .isInstanceOf(List.class); + assertThat(configuration + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_REQUEST_PREPROCESSOR)) + .isInstanceOf(OperationRequestPreprocessor.class); + assertThat(configuration + .get(RestDocumentationGenerator.ATTRIBUTE_NAME_DEFAULT_OPERATION_RESPONSE_PREPROCESSOR)) + .isInstanceOf(OperationResponsePreprocessor.class); } } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java index 57ff2a10..83e70738 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/RestAssuredRestDocumentationIntegrationTests.java @@ -17,12 +17,17 @@ package org.springframework.restdocs.restassured3; import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; import java.net.URL; import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; import java.util.regex.Pattern; import io.restassured.builder.RequestSpecBuilder; import io.restassured.specification.RequestSpecification; +import org.assertj.core.api.Condition; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; @@ -31,13 +36,12 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMethod; import static io.restassured.RestAssured.given; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.headers.HeaderDocumentation.responseHeaders; import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.linkWithRel; @@ -61,10 +65,9 @@ import static org.springframework.restdocs.request.RequestDocumentation.requestP import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor; -import static org.springframework.restdocs.test.SnippetMatchers.codeBlock; -import static org.springframework.restdocs.test.SnippetMatchers.httpRequest; -import static org.springframework.restdocs.test.SnippetMatchers.httpResponse; -import static org.springframework.restdocs.test.SnippetMatchers.snippet; +import static org.springframework.restdocs.test.SnippetConditions.codeBlock; +import static org.springframework.restdocs.test.SnippetConditions.httpRequest; +import static org.springframework.restdocs.test.SnippetConditions.httpResponse; /** * Integration tests for using Spring REST Docs with REST Assured. @@ -100,13 +103,13 @@ public class RestAssuredRestDocumentationIntegrationTests { .statusCode(200); assertThat(new File( - "build/generated-snippets/curl-snippet-with-content/curl-request.adoc"), - is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") - .content(String.format("$ curl 'http://localhost:" - + tomcat.getPort() + "/' -i -X POST \\%n" - + " -H 'Accept: application/json' \\%n" - + " -H 'Content-Type: " + contentType + "' \\%n" - + " -d 'content'"))))); + "build/generated-snippets/curl-snippet-with-content/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash") + .withContent(String.format("$ curl 'http://localhost:" + + tomcat.getPort() + "/' -i -X POST \\%n" + + " -H 'Accept: application/json' \\%n" + + " -H 'Content-Type: " + contentType + + "' \\%n" + " -d 'content'")))); } @Test @@ -118,13 +121,14 @@ public class RestAssuredRestDocumentationIntegrationTests { .contentType(contentType).cookie("cookieName", "cookieVal").get("/") .then().statusCode(200); assertThat(new File( - "build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc"), - is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") - .content(String.format("$ curl 'http://localhost:" - + tomcat.getPort() + "/' -i -X GET \\%n" - + " -H 'Accept: application/json' \\%n" - + " -H 'Content-Type: " + contentType + "' \\%n" - + " --cookie 'cookieName=cookieVal'"))))); + "build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash") + .withContent(String.format("$ curl 'http://localhost:" + + tomcat.getPort() + "/' -i -X GET \\%n" + + " -H 'Accept: application/json' \\%n" + + " -H 'Content-Type: " + contentType + + "' \\%n" + + " --cookie 'cookieName=cookieVal'")))); } @Test @@ -136,13 +140,13 @@ public class RestAssuredRestDocumentationIntegrationTests { .post("/?foo=bar").then().statusCode(200); String contentType = "application/x-www-form-urlencoded; charset=ISO-8859-1"; assertThat(new File( - "build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc"), - is(snippet(asciidoctor()).withContents(codeBlock(asciidoctor(), "bash") - .content(String.format("$ curl " + "'http://localhost:" - + tomcat.getPort() + "/?foo=bar' -i -X POST \\%n" - + " -H 'Accept: application/json' \\%n" - + " -H 'Content-Type: " + contentType + "' \\%n" - + " -d 'a=alpha'"))))); + "build/generated-snippets/curl-snippet-with-query-string/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent( + String.format("$ curl " + "'http://localhost:" + + tomcat.getPort() + "/?foo=bar' -i -X POST \\%n" + + " -H 'Accept: application/json' \\%n" + + " -H 'Content-Type: " + contentType + + "' \\%n" + " -d 'a=alpha'")))); } @Test @@ -219,7 +223,6 @@ public class RestAssuredRestDocumentationIntegrationTests { subsectionWithPath("links") .description("Links to other resources")))) .accept("application/json").get("/").then().statusCode(200); - assertExpectedSnippetFilesExist( new File("build/generated-snippets/response-fields"), "http-request.adoc", "http-response.adoc", "curl-request.adoc", "response-fields.adoc"); @@ -281,12 +284,10 @@ public class RestAssuredRestDocumentationIntegrationTests { .get("/set-cookie").then().statusCode(200); assertExpectedSnippetFilesExist(new File("build/generated-snippets/set-cookie"), "http-request.adoc", "http-response.adoc", "curl-request.adoc"); - - assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc"), - is(snippet(asciidoctor()) - .withContents(httpResponse(asciidoctor(), HttpStatus.OK).header( - HttpHeaders.SET_COOKIE, - "name=value; Domain=localhost; HttpOnly")))); + assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc")) + .has(content(httpResponse(asciidoctor(), HttpStatus.OK).header( + HttpHeaders.SET_COOKIE, + "name=value; Domain=localhost; HttpOnly"))); } @Test @@ -304,24 +305,22 @@ public class RestAssuredRestDocumentationIntegrationTests { removeHeaders("a", HttpHeaders.CONTENT_LENGTH)))) .get("/").then().statusCode(200); assertThat( - new File("build/generated-snippets/original-request/http-request.adoc"), - is(snippet(asciidoctor()) - .withContents(httpRequest(asciidoctor(), RequestMethod.GET, "/") + new File("build/generated-snippets/original-request/http-request.adoc")) + .has(content(httpRequest(asciidoctor(), RequestMethod.GET, "/") .header("a", "alpha").header("b", "bravo") .header("Accept", MediaType.APPLICATION_JSON_VALUE) .header("Content-Type", "application/json; charset=UTF-8") .header("Host", "localhost:" + tomcat.getPort()) .header("Content-Length", "13") - .content("{\"a\":\"alpha\"}")))); + .content("{\"a\":\"alpha\"}"))); String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); assertThat(new File( - "build/generated-snippets/preprocessed-request/http-request.adoc"), - is(snippet(asciidoctor()) - .withContents(httpRequest(asciidoctor(), RequestMethod.GET, "/") + "build/generated-snippets/preprocessed-request/http-request.adoc")) + .has(content(httpRequest(asciidoctor(), RequestMethod.GET, "/") .header("b", "bravo") .header("Accept", MediaType.APPLICATION_JSON_VALUE) .header("Content-Type", "application/json; charset=UTF-8") - .header("Host", "localhost").content(prettyPrinted)))); + .header("Host", "localhost").content(prettyPrinted))); } @Test @@ -339,13 +338,12 @@ public class RestAssuredRestDocumentationIntegrationTests { .statusCode(200); String prettyPrinted = String.format("{%n \"a\" : \"<>\"%n}"); assertThat(new File( - "build/generated-snippets/default-preprocessed-request/http-request.adoc"), - is(snippet(asciidoctor()) - .withContents(httpRequest(asciidoctor(), RequestMethod.GET, "/") + "build/generated-snippets/default-preprocessed-request/http-request.adoc")) + .has(content(httpRequest(asciidoctor(), RequestMethod.GET, "/") .header("b", "bravo") .header("Accept", MediaType.APPLICATION_JSON_VALUE) .header("Content-Type", "application/json; charset=UTF-8") - .header("Host", "localhost").content(prettyPrinted)))); + .header("Host", "localhost").content(prettyPrinted))); } @Test @@ -363,14 +361,13 @@ public class RestAssuredRestDocumentationIntegrationTests { String prettyPrinted = String.format("{%n \"a\" : \"<>\",%n \"links\" : " + "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}"); assertThat(new File( - "build/generated-snippets/preprocessed-response/http-response.adoc"), - is(snippet(asciidoctor()) - .withContents(httpResponse(asciidoctor(), HttpStatus.OK) + "build/generated-snippets/preprocessed-response/http-response.adoc")) + .has(content(httpResponse(asciidoctor(), HttpStatus.OK) .header("Foo", "https://api.example.com/foo/bar") .header("Content-Type", "application/json;charset=UTF-8") .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) - .content(prettyPrinted)))); + .content(prettyPrinted))); } @Test @@ -389,14 +386,13 @@ public class RestAssuredRestDocumentationIntegrationTests { String prettyPrinted = String.format("{%n \"a\" : \"<>\",%n \"links\" : " + "[ {%n \"rel\" : \"rel\",%n \"href\" : \"...\"%n } ]%n}"); assertThat(new File( - "build/generated-snippets/default-preprocessed-response/http-response.adoc"), - is(snippet(asciidoctor()) - .withContents(httpResponse(asciidoctor(), HttpStatus.OK) + "build/generated-snippets/default-preprocessed-response/http-response.adoc")) + .has(content(httpResponse(asciidoctor(), HttpStatus.OK) .header("Foo", "https://api.example.com/foo/bar") .header("Content-Type", "application/json;charset=UTF-8") .header(HttpHeaders.CONTENT_LENGTH, prettyPrinted.getBytes().length) - .content(prettyPrinted)))); + .content(prettyPrinted))); } @Test @@ -416,15 +412,33 @@ public class RestAssuredRestDocumentationIntegrationTests { Thread.currentThread().setContextClassLoader(previous); } assertThat(new File( - "build/generated-snippets/custom-snippet-template/curl-request.adoc"), - is(snippet(asciidoctor()).withContents(equalTo("Custom curl request")))); + "build/generated-snippets/custom-snippet-template/curl-request.adoc")) + .hasContent("Custom curl request"); } private void assertExpectedSnippetFilesExist(File directory, String... snippets) { for (String snippet : snippets) { - File snippetFile = new File(directory, snippet); - assertTrue("Snippet " + snippetFile + " not found", snippetFile.isFile()); + assertThat(new File(directory, snippet)).isFile(); } } + private Condition content(final Condition delegate) { + return new Condition() { + + @Override + public boolean matches(File value) { + try { + return delegate + .matches(FileCopyUtils.copyToString(new InputStreamReader( + new FileInputStream(value), StandardCharsets.UTF_8))); + } + catch (IOException ex) { + fail("Failed to read '" + value + "'", ex); + return false; + } + } + + }; + } + } diff --git a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java index 3f21b9ad..7422588b 100644 --- a/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java +++ b/spring-restdocs-restassured/src/test/java/org/springframework/restdocs/restassured3/operation/preprocess/UriModifyingOperationPreprocessorTests.java @@ -35,9 +35,7 @@ import org.springframework.restdocs.operation.OperationResponseFactory; import org.springframework.restdocs.operation.Parameters; import org.springframework.restdocs.operation.RequestCookie; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link UriModifyingOperationPreprocessor}. @@ -58,8 +56,7 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://localhost:12345")); - assertThat(processed.getUri(), - is(equalTo(URI.create("https://localhost:12345")))); + assertThat(processed.getUri()).isEqualTo(URI.create("https://localhost:12345")); } @Test @@ -67,10 +64,10 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.host("api.example.com"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.foo.com:12345")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com:12345")))); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST), - is(equalTo("api.example.com:12345"))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com:12345")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)) + .isEqualTo("api.example.com:12345"); } @Test @@ -78,10 +75,10 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.port(23456); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com:23456")))); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST), - is(equalTo("api.example.com:23456"))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com:23456")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)) + .isEqualTo("api.example.com:23456"); } @Test @@ -89,9 +86,9 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345")); - assertThat(processed.getUri(), is(equalTo(URI.create("http://api.example.com")))); - assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST), - is(equalTo("api.example.com"))); + assertThat(processed.getUri()).isEqualTo(URI.create("http://api.example.com")); + assertThat(processed.getHeaders().getFirst(HttpHeaders.HOST)) + .isEqualTo("api.example.com"); } @Test @@ -99,8 +96,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345/foo/bar")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com/foo/bar")))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com/foo/bar")); } @Test @@ -108,8 +105,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345?foo=bar")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com?foo=bar")))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com?foo=bar")); } @Test @@ -117,8 +114,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.removePort(); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://api.example.com:12345#foo")); - assertThat(processed.getUri(), - is(equalTo(URI.create("http://api.example.com#foo")))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("http://api.example.com#foo")); } @Test @@ -127,8 +124,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'https://localhost:12345' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'https://localhost:12345' should be used"); } @Test @@ -137,8 +134,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://api.example.com:12345' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://api.example.com:12345' should be used"); } @Test @@ -147,8 +144,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost:23456' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost:23456' should be used"); } @Test @@ -157,8 +154,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost' should be used"); } @Test @@ -167,8 +164,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); - assertThat(new String(processed.getContent()), is(equalTo( - "Use 'http://localhost' or 'https://localhost' to access the service"))); + assertThat(new String(processed.getContent())).isEqualTo( + "Use 'http://localhost' or 'https://localhost' to access the service"); } @Test @@ -177,8 +174,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345/foo/bar' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost/foo/bar' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost/foo/bar' should be used"); } @Test @@ -187,8 +184,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345?foo=bar' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost?foo=bar' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost?foo=bar' should be used"); } @Test @@ -197,8 +194,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor .preprocess(createRequestWithContent( "The uri 'http://localhost:12345#foo' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost#foo' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost#foo' should be used"); } @Test @@ -207,8 +204,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'https://localhost:12345' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'https://localhost:12345' should be used"); } @Test @@ -217,8 +214,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://api.example.com:12345' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://api.example.com:12345' should be used"); } @Test @@ -227,8 +224,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost:23456' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost:23456' should be used"); } @Test @@ -237,8 +234,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost' should be used"); } @Test @@ -247,8 +244,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "Use 'http://localhost:12345' or 'https://localhost:23456' to access the service")); - assertThat(new String(processed.getContent()), is(equalTo( - "Use 'http://localhost' or 'https://localhost' to access the service"))); + assertThat(new String(processed.getContent())).isEqualTo( + "Use 'http://localhost' or 'https://localhost' to access the service"); } @Test @@ -257,8 +254,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345/foo/bar' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost/foo/bar' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost/foo/bar' should be used"); } @Test @@ -267,8 +264,8 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345?foo=bar' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost?foo=bar' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost?foo=bar' should be used"); } @Test @@ -277,34 +274,33 @@ public class UriModifyingOperationPreprocessorTests { OperationResponse processed = this.preprocessor .preprocess(createResponseWithContent( "The uri 'http://localhost:12345#foo' should be used")); - assertThat(new String(processed.getContent()), - is(equalTo("The uri 'http://localhost#foo' should be used"))); + assertThat(new String(processed.getContent())) + .isEqualTo("The uri 'http://localhost#foo' should be used"); } @Test public void urisInRequestHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com") .preprocess(createRequestWithHeader("Foo", "http://locahost:12345")); - assertThat(processed.getHeaders().getFirst("Foo"), - is(equalTo("http://api.example.com:12345"))); - assertThat(processed.getHeaders().getFirst("Host"), - is(equalTo("api.example.com"))); + assertThat(processed.getHeaders().getFirst("Foo")) + .isEqualTo("http://api.example.com:12345"); + assertThat(processed.getHeaders().getFirst("Host")).isEqualTo("api.example.com"); } @Test public void urisInResponseHeadersCanBeModified() { OperationResponse processed = this.preprocessor.host("api.example.com") .preprocess(createResponseWithHeader("Foo", "http://locahost:12345")); - assertThat(processed.getHeaders().getFirst("Foo"), - is(equalTo("http://api.example.com:12345"))); + assertThat(processed.getHeaders().getFirst("Foo")) + .isEqualTo("http://api.example.com:12345"); } @Test public void urisInRequestPartHeadersCanBeModified() { OperationRequest processed = this.preprocessor.host("api.example.com").preprocess( createRequestWithPartWithHeader("Foo", "http://locahost:12345")); - assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo"), - is(equalTo("http://api.example.com:12345"))); + assertThat(processed.getParts().iterator().next().getHeaders().getFirst("Foo")) + .isEqualTo("http://api.example.com:12345"); } @Test @@ -312,8 +308,8 @@ public class UriModifyingOperationPreprocessorTests { OperationRequest processed = this.preprocessor.host("api.example.com") .preprocess(createRequestWithPartWithContent( "The uri 'http://localhost:12345' should be used")); - assertThat(new String(processed.getParts().iterator().next().getContent()), - is(equalTo("The uri 'http://api.example.com:12345' should be used"))); + assertThat(new String(processed.getParts().iterator().next().getContent())) + .isEqualTo("The uri 'http://api.example.com:12345' should be used"); } @Test @@ -321,8 +317,8 @@ public class UriModifyingOperationPreprocessorTests { this.preprocessor.scheme("https"); OperationRequest processed = this.preprocessor .preprocess(createRequestWithUri("http://localhost:12345?foo=%7B%7D")); - assertThat(processed.getUri(), - is(equalTo(URI.create("https://localhost:12345?foo=%7B%7D")))); + assertThat(processed.getUri()) + .isEqualTo(URI.create("https://localhost:12345?foo=%7B%7D")); } @@ -334,7 +330,7 @@ public class UriModifyingOperationPreprocessorTests { new HttpHeaders(), new Parameters(), Collections.emptyList(), cookies); OperationRequest processed = this.preprocessor.preprocess(request); - assertThat(processed.getCookies().size(), is(equalTo(1))); + assertThat(processed.getCookies().size()).isEqualTo(1); } private OperationRequest createRequestWithUri(String uri) { diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java index bd5264f8..74300f04 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRequestConverterTests.java @@ -18,7 +18,6 @@ package org.springframework.restdocs.webtestclient; import java.net.URI; import java.util.Arrays; -import java.util.Iterator; import org.junit.Test; @@ -29,7 +28,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.restdocs.operation.OperationRequest; import org.springframework.restdocs.operation.OperationRequestPart; -import org.springframework.restdocs.operation.RequestCookie; import org.springframework.test.web.reactive.server.ExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.util.LinkedMultiValueMap; @@ -39,12 +37,7 @@ import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.POST; @@ -64,8 +57,8 @@ public class WebTestClientRequestConverterTests { .configureClient().baseUrl("http://localhost").build().get().uri("/foo") .exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test @@ -75,8 +68,8 @@ public class WebTestClientRequestConverterTests { .configureClient().baseUrl("http://localhost:8080").build().get() .uri("/foo").exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("http://localhost:8080/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost:8080/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test @@ -87,10 +80,11 @@ public class WebTestClientRequestConverterTests { .header("a", "alpha", "apple").header("b", "bravo").exchange() .expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); - assertThat(request.getHeaders(), hasEntry("a", Arrays.asList("alpha", "apple"))); - assertThat(request.getHeaders(), hasEntry("b", Arrays.asList("bravo"))); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(request.getHeaders()).containsEntry("a", + Arrays.asList("alpha", "apple")); + assertThat(request.getHeaders()).containsEntry("b", Arrays.asList("bravo")); } @Test @@ -100,8 +94,8 @@ public class WebTestClientRequestConverterTests { .configureClient().baseUrl("https://localhost").build().get().uri("/foo") .exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("https://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("https://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test @@ -111,8 +105,8 @@ public class WebTestClientRequestConverterTests { .configureClient().baseUrl("https://localhost:8443").build().get() .uri("/foo").exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("https://localhost:8443/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()).isEqualTo(URI.create("https://localhost:8443/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test @@ -122,12 +116,12 @@ public class WebTestClientRequestConverterTests { .configureClient().baseUrl("http://localhost").build().get() .uri("/foo?a=alpha&b=bravo").exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), - is(URI.create("http://localhost/foo?a=alpha&b=bravo"))); - assertThat(request.getParameters().size(), is(2)); - assertThat(request.getParameters(), hasEntry("a", Arrays.asList("alpha"))); - assertThat(request.getParameters(), hasEntry("b", Arrays.asList("bravo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); + assertThat(request.getUri()) + .isEqualTo(URI.create("http://localhost/foo?a=alpha&b=bravo")); + assertThat(request.getParameters()).hasSize(2); + assertThat(request.getParameters()).containsEntry("a", Arrays.asList("alpha")); + assertThat(request.getParameters()).containsEntry("b", Arrays.asList("bravo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); } @Test @@ -143,12 +137,12 @@ public class WebTestClientRequestConverterTests { .uri("/foo").body(BodyInserters.fromFormData(parameters)).exchange() .expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); - assertThat(request.getParameters().size(), is(2)); - assertThat(request.getParameters(), - hasEntry("a", Arrays.asList("alpha", "apple"))); - assertThat(request.getParameters(), hasEntry("b", Arrays.asList("br&vo"))); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getParameters()).hasSize(2); + assertThat(request.getParameters()).containsEntry("a", + Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @Test @@ -161,13 +155,13 @@ public class WebTestClientRequestConverterTests { .uri(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")) .exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), - is(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); - assertThat(request.getParameters().size(), is(2)); - assertThat(request.getParameters(), - hasEntry("a", Arrays.asList("alpha", "apple"))); - assertThat(request.getParameters(), hasEntry("b", Arrays.asList("br&vo"))); + assertThat(request.getUri()) + .isEqualTo(URI.create("http://localhost/foo?a=alpha&a=apple&b=br%26vo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getParameters()).hasSize(2); + assertThat(request.getParameters()).containsEntry("a", + Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @Test @@ -183,13 +177,13 @@ public class WebTestClientRequestConverterTests { .body(BodyInserters.fromFormData(parameters)).exchange().expectBody() .returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), - is(URI.create("http://localhost/foo?a=alpha&b=br%26vo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); - assertThat(request.getParameters().size(), is(2)); - assertThat(request.getParameters(), - hasEntry("a", Arrays.asList("alpha", "apple"))); - assertThat(request.getParameters(), hasEntry("b", Arrays.asList("br&vo"))); + assertThat(request.getUri()) + .isEqualTo(URI.create("http://localhost/foo?a=alpha&b=br%26vo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getParameters()).hasSize(2); + assertThat(request.getParameters()).containsEntry("a", + Arrays.asList("alpha", "apple")); + assertThat(request.getParameters()).containsEntry("b", Arrays.asList("br&vo")); } @Test @@ -200,8 +194,8 @@ public class WebTestClientRequestConverterTests { .configureClient().baseUrl("http://localhost").build().post().uri("/foo") .exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); } @Test @@ -216,17 +210,16 @@ public class WebTestClientRequestConverterTests { .uri("/foo").body(BodyInserters.fromMultipartData(multipartData)) .exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); - assertThat(request.getParts().size(), is(1)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getParts()).hasSize(1); OperationRequestPart part = request.getParts().iterator().next(); - assertThat(part.getName(), is(equalTo("file"))); - assertThat(part.getSubmittedFileName(), is(nullValue())); - assertThat(part.getHeaders().size(), is(2)); - assertThat(part.getHeaders().getContentLength(), is(4L)); - assertThat(part.getHeaders().getContentDisposition().getName(), - is(equalTo("file"))); - assertThat(part.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 }))); + assertThat(part.getName()).isEqualTo("file"); + assertThat(part.getSubmittedFileName()).isNull(); + assertThat(part.getHeaders()).hasSize(2); + assertThat(part.getHeaders().getContentLength()).isEqualTo(4L); + assertThat(part.getHeaders().getContentDisposition().getName()).isEqualTo("file"); + assertThat(part.getContent()).containsExactly(1, 2, 3, 4); } @Test @@ -248,19 +241,19 @@ public class WebTestClientRequestConverterTests { .uri("/foo").body(BodyInserters.fromMultipartData(multipartData)) .exchange().expectBody().returnResult(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.POST)); - assertThat(request.getParts().size(), is(1)); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.POST); + assertThat(request.getParts()).hasSize(1); OperationRequestPart part = request.getParts().iterator().next(); - assertThat(part.getName(), is(equalTo("file"))); - assertThat(part.getSubmittedFileName(), is(equalTo("image.png"))); - assertThat(part.getHeaders().size(), is(3)); - assertThat(part.getHeaders().getContentLength(), is(4L)); + assertThat(part.getName()).isEqualTo("file"); + assertThat(part.getSubmittedFileName()).isEqualTo("image.png"); + assertThat(part.getHeaders()).hasSize(3); + assertThat(part.getHeaders().getContentLength()).isEqualTo(4); ContentDisposition contentDisposition = part.getHeaders().getContentDisposition(); - assertThat(contentDisposition.getName(), is(equalTo("file"))); - assertThat(contentDisposition.getFilename(), is(equalTo("image.png"))); - assertThat(part.getHeaders().getContentType(), is(equalTo(MediaType.IMAGE_PNG))); - assertThat(part.getContent(), is(equalTo(new byte[] { 1, 2, 3, 4 }))); + assertThat(contentDisposition.getName()).isEqualTo("file"); + assertThat(contentDisposition.getFilename()).isEqualTo("image.png"); + assertThat(part.getHeaders().getContentType()).isEqualTo(MediaType.IMAGE_PNG); + assertThat(part.getContent()).containsExactly(1, 2, 3, 4); } @Test @@ -270,20 +263,16 @@ public class WebTestClientRequestConverterTests { .configureClient().baseUrl("http://localhost").build().get().uri("/foo") .cookie("cookieName1", "cookieVal1").cookie("cookieName2", "cookieVal2") .exchange().expectBody().returnResult(); - assertThat(result.getRequestHeaders().get(HttpHeaders.COOKIE), - is(notNullValue())); + assertThat(result.getRequestHeaders().get(HttpHeaders.COOKIE)).isNotNull(); OperationRequest request = this.converter.convert(result); - assertThat(request.getUri(), is(URI.create("http://localhost/foo"))); - assertThat(request.getMethod(), is(HttpMethod.GET)); - assertThat(request.getCookies().size(), is(equalTo(2))); - assertThat(request.getHeaders().get(HttpHeaders.COOKIE), is(nullValue())); - Iterator cookieIterator = request.getCookies().iterator(); - RequestCookie cookie1 = cookieIterator.next(); - assertThat(cookie1.getName(), is(equalTo("cookieName1"))); - assertThat(cookie1.getValue(), is(equalTo("cookieVal1"))); - RequestCookie cookie2 = cookieIterator.next(); - assertThat(cookie2.getName(), is(equalTo("cookieName2"))); - assertThat(cookie2.getValue(), is(equalTo("cookieVal2"))); + assertThat(request.getUri()).isEqualTo(URI.create("http://localhost/foo")); + assertThat(request.getMethod()).isEqualTo(HttpMethod.GET); + assertThat(request.getCookies()).hasSize(2); + assertThat(request.getHeaders().get(HttpHeaders.COOKIE)).isNull(); + assertThat(request.getCookies()).extracting("name").containsExactly("cookieName1", + "cookieName2"); + assertThat(request.getCookies()).extracting("value").containsExactly("cookieVal1", + "cookieVal2"); } } diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java index 2e868e4d..01fec722 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientResponseConverterTests.java @@ -30,10 +30,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; /** @@ -53,11 +50,11 @@ public class WebTestClientResponseConverterTests { .configureClient().baseUrl("http://localhost").build().get().uri("/foo") .exchange().expectBody().returnResult(); OperationResponse response = this.converter.convert(result); - assertThat(response.getStatus(), is(HttpStatus.OK)); - assertThat(response.getContentAsString(), is(equalTo("Hello, World!"))); - assertThat(response.getHeaders().getContentType(), - is(MediaType.parseMediaType("text/plain;charset=UTF-8"))); - assertThat(response.getHeaders().getContentLength(), is(13L)); + assertThat(response.getStatus()).isEqualTo(HttpStatus.OK); + assertThat(response.getContentAsString()).isEqualTo("Hello, World!"); + assertThat(response.getHeaders().getContentType()) + .isEqualTo(MediaType.parseMediaType("text/plain;charset=UTF-8")); + assertThat(response.getHeaders().getContentLength()).isEqualTo(13); } @Test @@ -71,10 +68,9 @@ public class WebTestClientResponseConverterTests { .configureClient().baseUrl("http://localhost").build().get().uri("/foo") .exchange().expectBody().returnResult(); OperationResponse response = this.converter.convert(result); - assertThat(response.getHeaders().size(), is(1)); - assertTrue(response.getHeaders().containsKey(HttpHeaders.SET_COOKIE)); - assertThat(response.getHeaders().get(HttpHeaders.SET_COOKIE), equalTo( - Collections.singletonList("name=value; Domain=localhost; HttpOnly"))); + assertThat(response.getHeaders()).hasSize(1); + assertThat(response.getHeaders()).containsEntry(HttpHeaders.SET_COOKIE, + Collections.singletonList("name=value; Domain=localhost; HttpOnly")); } } diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java index 9a1bfe7c..759a2771 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationConfigurerTests.java @@ -17,7 +17,6 @@ package org.springframework.restdocs.webtestclient; import java.net.URI; -import java.util.Map; import org.junit.Rule; import org.junit.Test; @@ -29,11 +28,7 @@ import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.client.ClientRequest; import org.springframework.web.reactive.function.client.ExchangeFunction; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -55,11 +50,10 @@ public class WebTestClientRestDocumentationConfigurerTests { ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("/test")) .header(WebTestClient.WEBTESTCLIENT_REQUEST_ID, "1").build(); this.configurer.filter(request, mock(ExchangeFunction.class)); - Map configuration = WebTestClientRestDocumentationConfigurer - .retrieveConfiguration(request.headers()); - assertThat(configuration, notNullValue()); assertThat(WebTestClientRestDocumentationConfigurer - .retrieveConfiguration(request.headers()), nullValue()); + .retrieveConfiguration(request.headers())).isNotNull(); + assertThat(WebTestClientRestDocumentationConfigurer + .retrieveConfiguration(request.headers())).isNull(); } @Test @@ -72,8 +66,8 @@ public class WebTestClientRestDocumentationConfigurerTests { ArgumentCaptor requestCaptor = ArgumentCaptor .forClass(ClientRequest.class); verify(exchangeFunction).exchange(requestCaptor.capture()); - assertThat(requestCaptor.getValue().url(), - is(equalTo(URI.create("http://localhost:8080/test?foo=bar#baz")))); + assertThat(requestCaptor.getValue().url()) + .isEqualTo(URI.create("http://localhost:8080/test?foo=bar#baz")); } @Test @@ -87,8 +81,8 @@ public class WebTestClientRestDocumentationConfigurerTests { ArgumentCaptor requestCaptor = ArgumentCaptor .forClass(ClientRequest.class); verify(exchangeFunction).exchange(requestCaptor.capture()); - assertThat(requestCaptor.getValue().url(), - is(equalTo(URI.create("https://api.example.com:4567/test?foo=bar#baz")))); + assertThat(requestCaptor.getValue().url()) + .isEqualTo(URI.create("https://api.example.com:4567/test?foo=bar#baz")); } } diff --git a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java index 29c94c65..1dbd9fc8 100644 --- a/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java +++ b/spring-restdocs-webtestclient/src/test/java/org/springframework/restdocs/webtestclient/WebTestClientRestDocumentationIntegrationTests.java @@ -17,6 +17,10 @@ package org.springframework.restdocs.webtestclient; import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -24,6 +28,7 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.assertj.core.api.Condition; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -36,6 +41,7 @@ import org.springframework.restdocs.JUnitRestDocumentation; import org.springframework.restdocs.templates.TemplateFormats; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.util.FileCopyUtils; import org.springframework.util.FileSystemUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -46,20 +52,18 @@ import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; import static org.springframework.restdocs.request.RequestDocumentation.partWithName; import static org.springframework.restdocs.request.RequestDocumentation.pathParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; import static org.springframework.restdocs.request.RequestDocumentation.requestParts; import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor; -import static org.springframework.restdocs.test.SnippetMatchers.codeBlock; -import static org.springframework.restdocs.test.SnippetMatchers.httpResponse; -import static org.springframework.restdocs.test.SnippetMatchers.snippet; -import static org.springframework.restdocs.test.SnippetMatchers.tableWithHeader; -import static org.springframework.restdocs.test.SnippetMatchers.tableWithTitleAndHeader; +import static org.springframework.restdocs.test.SnippetConditions.codeBlock; +import static org.springframework.restdocs.test.SnippetConditions.httpResponse; +import static org.springframework.restdocs.test.SnippetConditions.tableWithHeader; +import static org.springframework.restdocs.test.SnippetConditions.tableWithTitleAndHeader; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; import static org.springframework.web.reactive.function.BodyInserters.fromObject; @@ -118,12 +122,12 @@ public class WebTestClientRestDocumentationIntegrationTests { parameterWithName("foo").description("Foo description"), parameterWithName("bar").description("Bar description")))); assertThat( - new File("build/generated-snippets/path-parameters/path-parameters.adoc"), - is(snippet(asciidoctor()).withContents( - tableWithTitleAndHeader(TemplateFormats.asciidoctor(), - "+/{foo}/{bar}+", "Parameter", "Description") - .row("`foo`", "Foo description") - .row("`bar`", "Bar description")))); + new File("build/generated-snippets/path-parameters/path-parameters.adoc")) + .has(content( + tableWithTitleAndHeader(TemplateFormats.asciidoctor(), + "+/{foo}/{bar}+", "Parameter", "Description") + .row("`foo`", "Foo description") + .row("`bar`", "Bar description"))); } @Test @@ -134,11 +138,11 @@ public class WebTestClientRestDocumentationIntegrationTests { parameterWithName("a").description("Alpha description"), parameterWithName("b").description("Bravo description")))); assertThat(new File( - "build/generated-snippets/request-parameters/request-parameters.adoc"), - is(snippet(asciidoctor()).withContents( - tableWithHeader(TemplateFormats.asciidoctor(), "Parameter", - "Description").row("`a`", "Alpha description").row("`b`", - "Bravo description")))); + "build/generated-snippets/request-parameters/request-parameters.adoc")) + .has(content(tableWithHeader(TemplateFormats.asciidoctor(), + "Parameter", "Description") + .row("`a`", "Alpha description") + .row("`b`", "Bravo description"))); } @Test @@ -152,22 +156,19 @@ public class WebTestClientRestDocumentationIntegrationTests { this.webTestClient.post().uri("/upload") .body(BodyInserters.fromMultipartData(multipartData)).exchange() .expectStatus().isOk().expectBody().consumeWith(documentation); - assertThat(new File("build/generated-snippets/multipart/request-parts.adoc"), - is(snippet(asciidoctor()) - .withContents(tableWithHeader(TemplateFormats.asciidoctor(), - "Part", "Description").row("`a`", "Part a").row("`b`", - "Part b")))); + assertThat(new File("build/generated-snippets/multipart/request-parts.adoc")) + .has(content(tableWithHeader(TemplateFormats.asciidoctor(), "Part", + "Description").row("`a`", "Part a").row("`b`", "Part b"))); } @Test public void responseWithSetCookie() throws Exception { this.webTestClient.get().uri("/set-cookie").exchange().expectStatus().isOk() .expectBody().consumeWith(document("set-cookie")); - assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc"), - is(snippet(asciidoctor()) - .withContents(httpResponse(asciidoctor(), HttpStatus.OK).header( - HttpHeaders.SET_COOKIE, - "name=value; Domain=localhost; HttpOnly")))); + assertThat(new File("build/generated-snippets/set-cookie/http-response.adoc")) + .has(content(httpResponse(asciidoctor(), HttpStatus.OK).header( + HttpHeaders.SET_COOKIE, + "name=value; Domain=localhost; HttpOnly"))); } @Test @@ -176,12 +177,11 @@ public class WebTestClientRestDocumentationIntegrationTests { .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() .expectBody().consumeWith(document("curl-snippet-with-cookies")); assertThat(new File( - "build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc"), - is(snippet(asciidoctor()) - .withContents(codeBlock(asciidoctor(), "bash").content(String + "build/generated-snippets/curl-snippet-with-cookies/curl-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent(String .format("$ curl 'https://api.example.com/' -i -X GET \\%n" + " -H 'Accept: application/json' \\%n" - + " --cookie 'cookieName=cookieVal'"))))); + + " --cookie 'cookieName=cookieVal'")))); } @Test @@ -190,12 +190,11 @@ public class WebTestClientRestDocumentationIntegrationTests { .accept(MediaType.APPLICATION_JSON).exchange().expectStatus().isOk() .expectBody().consumeWith(document("httpie-snippet-with-cookies")); assertThat(new File( - "build/generated-snippets/httpie-snippet-with-cookies/httpie-request.adoc"), - is(snippet(asciidoctor()) - .withContents(codeBlock(asciidoctor(), "bash").content( + "build/generated-snippets/httpie-snippet-with-cookies/httpie-request.adoc")) + .has(content(codeBlock(asciidoctor(), "bash").withContent( String.format("$ http GET 'https://api.example.com/' \\%n" + " 'Accept:application/json' \\%n" - + " 'Cookie:cookieName=cookieVal'"))))); + + " 'Cookie:cookieName=cookieVal'")))); } private void assertExpectedSnippetFilesExist(File directory, String... snippets) { @@ -203,7 +202,26 @@ public class WebTestClientRestDocumentationIntegrationTests { Set expected = Stream.of(snippets) .map((snippet) -> new File(directory, snippet)) .collect(Collectors.toSet()); - assertThat(actual, equalTo(expected)); + assertThat(actual).isEqualTo(expected); + } + + private Condition content(final Condition delegate) { + return new Condition() { + + @Override + public boolean matches(File value) { + try { + return delegate + .matches(FileCopyUtils.copyToString(new InputStreamReader( + new FileInputStream(value), StandardCharsets.UTF_8))); + } + catch (IOException ex) { + fail("Failed to read '" + value + "'", ex); + return false; + } + } + + }; } /**