'Mockito - how to stub method on a real object?

Consider the following code:

class Foo {

   public void bar() {
      User user = new User(...);
      if (!user.isValid() {
         throw new SomeException();
      }
      ...
   }
}

In my Mockito unit test, I need to mock isValid method to return true when I test method bar.

I don't have access to the real User object that was constructed. Wondering how I can define my test unit logic. Essentially, I need isValid to return true for any User object. Thanks.

Note that I have rather simplified my code. The method isValid is called somewhere deep in the call stack. I



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source