Published 12 Oct, 2022

Java - How to test whether the object has been modified using Junit?

Category Java
Modified : Nov 30, 2022
80

I have a method.

void (Item item) {
}

I want to test in Junit whether item has been modified or not. Can some one tell me how do I do that ?

Answers

There are 2 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Java 8, Junit. These have been categorized in sections for a clear and precise explanation.

35

A method has to have a name.
So we will suppose you would mean :

void do (Item item) {
}

In the test method, you can store the state of the item by performing a deep copy of it before executing the method.
Then you execute the method.
At last, after the method is returned, you can check if the copy and the actual object have the same values in their fields that you want to compare.

For example by adding a copy constructor in Item to do a deep copy of it, you could write :

@Test
public void doWhenItemIsModified (Item item) {
   Item copyItem = item.deepCopy(item);
   instanceUnderTest.do(item);
   Assert.assertNotEquals(copyItem.getMyField(), item.getMyField())
   ... // assert other fields...
}

EDIT for comment :
You can implement the deepcopy in the Item class it is desirable to expose this constructor in the API of Item.
If it not the case you can add the deepcopy method in a utility test class.
And you could write something like : Item copyItem = UtilTest.deepCopyItem(item);


10

A much better approach would be to us item.hashCode(). If hashCode is correctly overridden in Item and every class within Item it will reflect every change (this is the idea behind hashCode).

    int old = item.hashCode();
    to.accept(item); //possible change here
    assertThat(item.hashCode(), is(old));

You should not override hashCode manually. You could use the IDE and let it generate hashCode and equals or you can use Lombok - for both ways you can chose the fields to be taken into account. In Java 14 you can use records (DTO class) they will have hashCode() and equals() implemented considering all fields.