简体   繁体   中英

test void method using mockito and Junit

i want test for void method using mockito and junit but after run the test will return exception NoSuchElementException

this code

@Spy
InMemory inMemoryGet;


@InjectMocks
UserService userService;

@Test
public void deleteUser(){
    User user=new User(2L,"abed","mohamed",26);
    userService.deleteUser(2L);
    verify(inMemoryGet,times(1)).deleteUser(2L);
}

InMemory class

    public void deleteUser(Long id) {
    System.out.println("users = " + users.size());
    users.remove(id,getById(id).get());
    System.out.println("users.size() = " + users.size());

}

and UserService class

    public void deleteUser(Long id) {
    inMemory.deleteUser(id);
}

work folw for test case UserService executed deleteId(id) method and then called in deleteId(id) in InMemory class and then InMemory completed the process

Note: in this test i don't have database just localdb after close application will delete all data

You have created 'user' in the test method, not in InMemory class. In other words, the created object 'user' does not exist in the 'users' list in InMemory bean. So during execution of deleteUser(), you see the exception NoSuchElementException. You have to add this object ( User user=new User(2L,"abed","mohamed",26) ) to 'users' List and then try to delete it.

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