0

Well, I'm doing simple test to understand junit and to be honest I don't understand why

@Test
void findById() {
    Long id= 2L;
    Visit returnedVisit = service.findById(id);
    assertEquals(Long.valueOf(4L),id);
}

id is equal 2 after changing value in tested method

public Visit findById(Long aLong) {
    aLong= 4L;
    return new Visit();
}
Ivan Lymar
  • 2,180
  • 11
  • 26
wwww
  • 760
  • 1
  • 11
  • 20

1 Answers1

2

This is because the local primitive variable id in one method (your test case) is set to 2. It is then passed by value to the other method. Passing by value means to put an exact bit-wise copy on the call stack. That called method sets its local copy of the variable, but that does not modify the caller's variable.

If you passed a list, you would see modifications, because the list reference is passed by value, and you can make changes to the list like adding new elements, and the caller's list is modified. You can also modify the reference to the list, but the caller won't see it, i.e., if you reassign the list to some new list in the called method, the caller will still have the old list.

This is just how Java passes parameters; it has nothing to do with JUnit.

See also this question and its answers.

Robert
  • 7,394
  • 40
  • 45
  • 64
  • Your comment is really helpful but if you add new element to list in method caller will actually see it – wwww Sep 05 '19 at 15:49