2

I have a method called JsonMarshall(T t) that takes an object and converts it into Json String. Inside this method I'm using the Objectmapper to accomplish this task:

mapper.writerWithDefaultPrettyPrinter().writeValueAsString(t)

Now, lets say I have a class ClientName with the attributes Title and Name that I'm using for my test. Now when I try to convert ClientName into json string with my method and test this method by asserting its output against some expected Json String such as:

expectedString =  "{\"title\":\"RandomTitle",\"Name\":\"RandomName\"}"

I get two scenarios:

  1. Test fails when I use mapper.writerWithDefaultPrettyPrinter().writeValueAsString(t) in my method.

  2. Test passes when I only do mapper.writeValueAsString(t)

So I guess the indentation of the writerWithDefaultPrettyPrinter() is causing the test to fail.

Any ideas how I can go about making this test pass for the first scenario?

Ganesh Satpute
  • 3,664
  • 6
  • 41
  • 78
Qad
  • 51
  • 3
  • 7

2 Answers2

1

I assume the first test fails because the output is pretty printed and contains additional format signs such as line breaks and whitespaces.

What you could do:

  1. Just use another expected string in the first test method.
  2. Parse the return string of your method under test and use the deserialized object for the test method.
  3. You can use a JsonPath lib for your test (Works similar to XPath). I use JsonPathResultMatcher to test RESTful Webservices based on the Spring Framework.
Patrick
  • 447
  • 8
  • 17
  • Of these three, I'd go for either (2) or (3). The problem with the first one is that the appearance of the "pretty-print" string could change (for example, in one version the indentation might be three spaces and in a new version the indentation gets changed to four spaces - or maybe the order of attributes changes), and that would break your unit test. Unless the *exact* appearance is important, I'd avoid testing against a particular fixed string. – dcsohl Sep 12 '16 at 18:10
1

As an alternative to @Patrick's perfectly reasonable options, I'd suggest a fourth choice: You can mock the Objectmapper with a tool like JMockit, Mockito or Easymock, and simply ensure that your JsonMarshall method calls the appropriate method(s) on Objectmapper.

This, of course, assumes that you have no doubts that mapper.writerWithDefaultPrettyPrinter().writeValueAsString() does what it is supposed to do and that it is what you want to do. If you have any doubts about either of these conditions, it would be best not to mock, at least for now.

dcsohl
  • 7,186
  • 1
  • 26
  • 44