jparams / to-string-verifier

To String Verifier provides an easy and convenient way to test the toString method on your class.
MIT License
32 stars 6 forks source link

String-formatter is erroneously applied to collections (and maps) with type string #24

Closed danielFesenmeyer closed 4 years ago

danielFesenmeyer commented 5 years ago

I have a class containing both a field of type String and of type Collection.

IntelliJ (Template "String concat (+) and super.toString()") generates the following code for this:

      @Override
      public String toString()
      {
         return "ClassWithStringAndStringCollection{" + "theString='" + theString + '\'' + ", theStringCollection="
            + theStringCollection + '}';
      }

When I write a test which checks that the string value is surrounded by apostrophs by configuring a corresponding formatter for type String, this formatter is erroneously also applied to each value in the collection, leading to the following failure:

Failed verification:
CustomStringFormatterShouldNotBeAppliedToCollectionsForIntelliJTest$ClassWithStringAndStringCollection

Expected auto generated toString:
ClassWithStringAndStringCollection{theString='ece92ceb-3625-4268-b18d-0a95bdc12b26', theStringCollection=[cf517611-c145-4258-8a3c-766ff13f3d6c]}

To contain fields with values:
  - theStringCollection: 'cf517611-c145-4258-8a3c-766ff13f3d6c'

Here is a test to reproduce:

import java.util.List;

import org.junit.Test;

import com.jparams.verifier.tostring.ToStringVerifier;
import com.jparams.verifier.tostring.preset.IntelliJPreset;

public class CustomStringFormatterShouldNotBeAppliedToCollectionsForIntelliJTest
{

   private static class ClassWithStringAndStringCollection
   {
      private String theString;
      private List<String> theStringCollection;

      @Override
      public String toString()
      {
         return "ClassWithStringAndStringCollection{" + "theString='" + theString + '\'' + ", theStringCollection="
            + theStringCollection + '}';
      }
   }

   @Test
   public void testToString() {
      ToStringVerifier.forClass(ClassWithStringAndStringCollection.class)
         .withPreset(new IntelliJPreset())
         .withFormatter(String.class, str -> '\'' + str  + '\'')
         .verify();
   }

}

Using a Map<String, String> instead of List produces a similar error.

jparams commented 4 years ago

Fixed in version 1.4.7