Skip to content

Latest commit

 

History

History
121 lines (92 loc) · 4.54 KB

PrintableWrappers.md

File metadata and controls

121 lines (92 loc) · 4.54 KB

How to Customize Another Object's toString()

Contents

* [Printable wrappers](#printable-wrappers)
* [Wrap a individual object](#wrap-a-individual-object)
  * [Label](#label)
  * [Alternative `toString()` Function](#alternative-tostring-function)
* [Wrap an array of objects](#wrap-an-array-of-objects)
* [Named objects](#named-objects)<!-- endToc -->

Printable wrappers

Sometimes an object's toString() is not suitable for a given situation. This is particularly true with the parameter names used with CombinationApprovals Printable wrappers gives you a way to control this.

Wrap a individual object

Label

If you just wanted to wrap a single object. You can create a printable wrapper by:

Printable<Integer> one = new Printable(1, "one");
assertEquals("one", one.toString());

snippet source | anchor

to access the value, simply call

Integer value = one.get();
assertEquals(1, value);

snippet source | anchor

Alternative toString() Function

You can also write a different function(lambda) to create the toString() and then apply it to the object.

Printable<Integer> two = new Printable(2, i -> "#" + i + ")");
assertEquals("#2)", two.toString());

snippet source | anchor

Wrap an array of objects

For convenience, if you want to do this to a whole list of items we have

Printable<Integer>[] numbers = Printable.create(n -> "#" + n, 1, 2, 3, 4, 5);
Approvals.verifyAll("Custom toString method", numbers, p -> String.format("%s -> %s", p, p.get()));

snippet source | anchor

would produce

Custom toString method


#1 -> 1
#2 -> 2
#3 -> 3
#4 -> 4
#5 -> 5

snippet source | anchor

Named objects

We also has a convenience builder if you want each object to have it's own label.

Printable<Integer>[] labeled = Printable.with().label(1, "first").label(2, "second").label(3, "third")
    .label(4, "forth").label(5, "fifth").toArray();
Approvals.verifyAll("Labeled", labeled, p -> String.format("%s -> %s", p, p.get()));

snippet source | anchor

would produce:

Labeled


first -> 1
second -> 2
third -> 3
forth -> 4
fifth -> 5

snippet source | anchor


Back to User Guide