'Adding test in JUnit that fails if Serialized Object changes

I have the following class that is created with the usage of a builder:

public class Foo {
  private String name;
  private int age;

  public String getName() { return name; }
  public int getAge() { return age; }

  private Foo(Builder b) {
    name = b.name;
    age = b.age;
  }

  public static final class Builder {
    private String name;
    private int age;

    public Builder name(String name) {
      this.name = name;
      return this;
    }

     public Builder age(int age) {
      this.age = age;
      return this;
    }
  }
}

Now I want to add a JUnit test for this where if this class were to change (via new field were to be added, some other changes made to this) that would also be reflected once the class got serialized, I want that test to fail to catch that change. I am not aware of any libraries that can do this, how can this be done?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source