简体   繁体   中英

using mockito to mock the class i'm testing

Let's say i have a controller class called UserController , and withing it there are 2 methods: getUserCount() and getLatestUser() , and getUserCount calls getLatestUser.

@Controller
class UserController{

public long getUserCount(){
#code
getLatestUser();
#code
}

public User getLatestUser(){}
}

i'm supposed to test each of these methods using Junit and Mockito, and thus i have something like this:

class UserControllerTest{
@Autowired
UserController userController;

@Test
public void testing_get_user_count(){
User user = new User();
when(userController.getLastestUser()).thenReturn(user);
}
}

My issue is that i can't mock UserController because i've autowired it, so i can't use when().thenReturn() on getLatestUser.

Is there a way for me to mock it anyways?

You can use @SpyBean instead of @Autowired . It applies Mockito spy on a bean.

class UserControllerTest {
  @SpyBean
  UserController userController;

  @Test
  public void testing_get_user_count(){
    User user = new User();
    when(userController.getLastestUser()).thenReturn(user);
  }
}

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