javaoopjunit

Java mock class construction


I am trying to understand what is exactly happening in this java unit test, as I managed to find that there is a possibility to pass values to Java class's constructor not inside the parentheses, but inside brackets after the classes parentheses, yet, don't seem to understand what is exactly happening right here in the attached unit test? My guess would be that it is creating a variable for that Subject class, but I don't need to create it inside my class's definition(declare a variable inside the class file/code)

        Subject s1 = fill(new Subject() {
            private static final long serialVersionUID = 1L;
        });

/* The class definition */
public class Subject {
    private int id;
    private String address;
    private String city;
    private String county;
    private String state;
    private String country;
    private String email;
    private String phone;
    private String web;
    private String zip;

// setters and getter for the declared variables here, also using default constructor

I tried googling but couldn't define what exactly I am trying to find, and the issue I am facing is that it is showing an error message of: The value of field new Subject(){}.serialVersionUID is not used <- as I understand that the serialVersionUID is somehow nested inside the Subject class, but not directly inside, will a getter be able to show it?


Solution

  • an error message of: The value of field new Subject(){}.serialVersionUID is not used

    That's a warning message, not an error message. It is emitted by the compiler because the field is declared, but not used by any code you have written, and the compiler suspects that it may be unused and therefore a programming mistake.

    However, the compiler is not omniscient, and one thing it can not take into account is access at runtime through the Reflection API. And it is possible such is happening here, because a field called serialVersionUID has a special role in Java Serialization.

    That is, if Java Serialization is used with this class, the field may be useful, and the warning spurious, in which case you can use @SuppressWarnings to silence the compiler.

    On the other hand, if this class is not used with Java Serialization, the field is indeed useless, and can be safely deleted.

    as I understand that the serialVersionUID is somehow nested inside the Subject class, but not directly inside, will a getter be able to show it?

    The syntax

    new Subject { 
        private static final long serialVersionUID = 1L;
    }
    

    declares an anonymous inner class that extends Subject, and instantiates it.