简体   繁体   中英

AssertionError on comparing different types of an object when unit testing my list user by id service

I'm trying to test a service in my API that when given a certain id, it should return user that corresponds to that id. Pretty straightforward, but i'm getting the following error that should be simple to fix but have no idea how:

java.lang.AssertionError: 
Expecting:
 <User(id=89, name=null, email=null)>
and actual:
 <Optional[User(id=89, name=null, email=null)]>
to refer to the same object

My test code is:

@RunWith(MockitoJUnitRunner.class)
public class ServiceDetailUserTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserDetailService userDetailService;

    @Test
    public void when_given_id_it_should_return_user() {
        User user = new User();
        user.setId(89L);

        when(userRepository.findById(user.getId())).thenReturn(Optional.of(user));

        Optional<User> expected = userDetailService.listUser(user.getId());

        assertThat(expected).isSameAs(user);
    }
}

And my service code (not even sure if needed) is:

@Service
public class UserDetailService {

    @Autowired
    UserRepository repository;

    public Optional<User> listUser(Long id) {
        return repository.findById(id);
    }
}

So, to compare my expected with my user , i need them to be the exact same type...but how? I've seen variations of this test, with one using the expression assertThat(expected).isNotNull(); instead of assertThat(expected).isSameAs(user); , but i'm not sure if that's correct.

This should work:

@Test
public void when_given_id_it_should_return_user() {
    User user = new User();
    user.setId(89L);

    Optional<User> userMock = Optional.of(user);

    when(userRepository.findById(user.getId())).thenReturn(userMock);

    Optional<User> expected = userDetailService.listUser(user.getId());

    assertEquals(expected, userMock);
}

This compares two instances of different types, since expected is an Optional, and user is a User:

assertThat(expected).isSameAs(user);

Either unwrap expected.get(), or make user an Optional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM