why did I get that error?
You are trying to mock addressRepository.findById(12)
here. When addressRepository.findById(12)
is called, you are saying that it should return Optional.of(myAddress)
. The thing is, it can't possibly return Optional.of(myAddress)
, which is an Optional<Address>
. findById
seems to be declared to return Address
, not Optional<Address>
.
When you remove Optional.of
, you are telling it to return just myAddress
, which it certainly can do. myAddress
is of type Address
, and findById
is declared to return an Address
.
In terms of the types involved, when
accepts a T
and returns an OngoingStubbing<T>
, which has a method called thenReturn
, which takes a T
. Since you passed an Address
into when
, T
is inferred to be Address
, and so thenReturn
takes an Address
too.
what's the difference in using or not using Optional.of?
As you have seen, using Optional.of
gives you an error, while not using it doesn't. It doesn't make sense to use Optional.of
here, unless findById
is declared to return Optional<Address>
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…