Home > front end >  using mockito to mock the class i'm testing
using mockito to mock the class i'm testing

Time:01-05

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?

CodePudding user response:

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);
  }
}
  •  Tags:  
  • Related