How can I test a spring-cloud-contract containing a java.time.Instant field











up vote
0
down vote

favorite












I want to test a contract where one field is of type java.time.Instant. But not all instances of an Instant are handled as I expect by spring-cloud-contract. Given the following simple contract:



Contract.make {
description("Get a version")
request {
method 'GET'
url '/config/version'
headers {
contentType(applicationJson())
}
}
response {
status 200
body(
nr: 42,
creationDate: producer(anyIso8601WithOffset())
)
headers {
contentType(applicationJson())
}
}
}


And this service implementation:



@RestController
public class VersionController {
@GetMapping(path = "/version")

public ResponseEntity<Version> getCurrentVersion() {
return ResponseEntity.ok(new Version(42, Instant.ofEpochMilli(0)));
}
}


Executing gradle test works fine. But if I replace the Instant with Instant.now(), my provider test fails with



java.lang.IllegalStateException: Parsed JSON [{"nr":42,"creationDate":"2018-11-11T15:28:26.958284Z"}] doesn't match the JSON path [$[?(@.['creationDate'] =~ /([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.d{3})?(Z|[+-][01]d:[0-5]d)/)]]


which is understandable because Instant.now() produces an Instant whose string representation does indeed not match the anyIso8601WithOffset() pattern. But why is this? Why are Instants represented differently and how can I describe a contract that validates for any instant?










share|improve this question




























    up vote
    0
    down vote

    favorite












    I want to test a contract where one field is of type java.time.Instant. But not all instances of an Instant are handled as I expect by spring-cloud-contract. Given the following simple contract:



    Contract.make {
    description("Get a version")
    request {
    method 'GET'
    url '/config/version'
    headers {
    contentType(applicationJson())
    }
    }
    response {
    status 200
    body(
    nr: 42,
    creationDate: producer(anyIso8601WithOffset())
    )
    headers {
    contentType(applicationJson())
    }
    }
    }


    And this service implementation:



    @RestController
    public class VersionController {
    @GetMapping(path = "/version")

    public ResponseEntity<Version> getCurrentVersion() {
    return ResponseEntity.ok(new Version(42, Instant.ofEpochMilli(0)));
    }
    }


    Executing gradle test works fine. But if I replace the Instant with Instant.now(), my provider test fails with



    java.lang.IllegalStateException: Parsed JSON [{"nr":42,"creationDate":"2018-11-11T15:28:26.958284Z"}] doesn't match the JSON path [$[?(@.['creationDate'] =~ /([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.d{3})?(Z|[+-][01]d:[0-5]d)/)]]


    which is understandable because Instant.now() produces an Instant whose string representation does indeed not match the anyIso8601WithOffset() pattern. But why is this? Why are Instants represented differently and how can I describe a contract that validates for any instant?










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I want to test a contract where one field is of type java.time.Instant. But not all instances of an Instant are handled as I expect by spring-cloud-contract. Given the following simple contract:



      Contract.make {
      description("Get a version")
      request {
      method 'GET'
      url '/config/version'
      headers {
      contentType(applicationJson())
      }
      }
      response {
      status 200
      body(
      nr: 42,
      creationDate: producer(anyIso8601WithOffset())
      )
      headers {
      contentType(applicationJson())
      }
      }
      }


      And this service implementation:



      @RestController
      public class VersionController {
      @GetMapping(path = "/version")

      public ResponseEntity<Version> getCurrentVersion() {
      return ResponseEntity.ok(new Version(42, Instant.ofEpochMilli(0)));
      }
      }


      Executing gradle test works fine. But if I replace the Instant with Instant.now(), my provider test fails with



      java.lang.IllegalStateException: Parsed JSON [{"nr":42,"creationDate":"2018-11-11T15:28:26.958284Z"}] doesn't match the JSON path [$[?(@.['creationDate'] =~ /([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.d{3})?(Z|[+-][01]d:[0-5]d)/)]]


      which is understandable because Instant.now() produces an Instant whose string representation does indeed not match the anyIso8601WithOffset() pattern. But why is this? Why are Instants represented differently and how can I describe a contract that validates for any instant?










      share|improve this question















      I want to test a contract where one field is of type java.time.Instant. But not all instances of an Instant are handled as I expect by spring-cloud-contract. Given the following simple contract:



      Contract.make {
      description("Get a version")
      request {
      method 'GET'
      url '/config/version'
      headers {
      contentType(applicationJson())
      }
      }
      response {
      status 200
      body(
      nr: 42,
      creationDate: producer(anyIso8601WithOffset())
      )
      headers {
      contentType(applicationJson())
      }
      }
      }


      And this service implementation:



      @RestController
      public class VersionController {
      @GetMapping(path = "/version")

      public ResponseEntity<Version> getCurrentVersion() {
      return ResponseEntity.ok(new Version(42, Instant.ofEpochMilli(0)));
      }
      }


      Executing gradle test works fine. But if I replace the Instant with Instant.now(), my provider test fails with



      java.lang.IllegalStateException: Parsed JSON [{"nr":42,"creationDate":"2018-11-11T15:28:26.958284Z"}] doesn't match the JSON path [$[?(@.['creationDate'] =~ /([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.d{3})?(Z|[+-][01]d:[0-5]d)/)]]


      which is understandable because Instant.now() produces an Instant whose string representation does indeed not match the anyIso8601WithOffset() pattern. But why is this? Why are Instants represented differently and how can I describe a contract that validates for any instant?







      json testing spring-cloud-contract java.time.instant






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 at 12:54









      Ole V.V.

      26.4k62651




      26.4k62651










      asked Nov 11 at 15:33









      Tobias Neubert

      114




      114
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Ok, I found a solution that works for me. Although I do not know if this is the way to go.



          In order to always get the exact same format of the serialized instant, I define the format of the corresponding property of my version bean as follows:



          public class Version {
          private final int nr;
          private final Instant creationDate;

          @JsonCreator
          public Version(
          @JsonProperty("nr") int nr,
          @JsonProperty("creationDate") Instant creationDate)
          {
          this.nr = nr;
          this.creationDate = creationDate;
          }

          public int getNr() {
          return nr;
          }

          @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX", timezone = "UTC")
          public Instant getCreationDate() {
          return creationDate;
          }
          }





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250263%2fhow-can-i-test-a-spring-cloud-contract-containing-a-java-time-instant-field%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            Ok, I found a solution that works for me. Although I do not know if this is the way to go.



            In order to always get the exact same format of the serialized instant, I define the format of the corresponding property of my version bean as follows:



            public class Version {
            private final int nr;
            private final Instant creationDate;

            @JsonCreator
            public Version(
            @JsonProperty("nr") int nr,
            @JsonProperty("creationDate") Instant creationDate)
            {
            this.nr = nr;
            this.creationDate = creationDate;
            }

            public int getNr() {
            return nr;
            }

            @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX", timezone = "UTC")
            public Instant getCreationDate() {
            return creationDate;
            }
            }





            share|improve this answer

























              up vote
              1
              down vote



              accepted










              Ok, I found a solution that works for me. Although I do not know if this is the way to go.



              In order to always get the exact same format of the serialized instant, I define the format of the corresponding property of my version bean as follows:



              public class Version {
              private final int nr;
              private final Instant creationDate;

              @JsonCreator
              public Version(
              @JsonProperty("nr") int nr,
              @JsonProperty("creationDate") Instant creationDate)
              {
              this.nr = nr;
              this.creationDate = creationDate;
              }

              public int getNr() {
              return nr;
              }

              @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX", timezone = "UTC")
              public Instant getCreationDate() {
              return creationDate;
              }
              }





              share|improve this answer























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                Ok, I found a solution that works for me. Although I do not know if this is the way to go.



                In order to always get the exact same format of the serialized instant, I define the format of the corresponding property of my version bean as follows:



                public class Version {
                private final int nr;
                private final Instant creationDate;

                @JsonCreator
                public Version(
                @JsonProperty("nr") int nr,
                @JsonProperty("creationDate") Instant creationDate)
                {
                this.nr = nr;
                this.creationDate = creationDate;
                }

                public int getNr() {
                return nr;
                }

                @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX", timezone = "UTC")
                public Instant getCreationDate() {
                return creationDate;
                }
                }





                share|improve this answer












                Ok, I found a solution that works for me. Although I do not know if this is the way to go.



                In order to always get the exact same format of the serialized instant, I define the format of the corresponding property of my version bean as follows:



                public class Version {
                private final int nr;
                private final Instant creationDate;

                @JsonCreator
                public Version(
                @JsonProperty("nr") int nr,
                @JsonProperty("creationDate") Instant creationDate)
                {
                this.nr = nr;
                this.creationDate = creationDate;
                }

                public int getNr() {
                return nr;
                }

                @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX", timezone = "UTC")
                public Instant getCreationDate() {
                return creationDate;
                }
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 11 at 19:46









                Tobias Neubert

                114




                114






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250263%2fhow-can-i-test-a-spring-cloud-contract-containing-a-java-time-instant-field%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues