0

We're migrating all our code away from PowerMock to Mockito Inline, I've mostly been able to migrate all cases but I don't know how to throw an exception when an instance of a specific class is created, using Mockito MockedConstruction.

i.e I need to migrate to Mockito Inline from this:

whenNew(MyClass.class).withAnyArguments().thenThrow(new MyException("fail"));

I've read the docs and I can't find how to do it.

I've tried this:

try (MockedConstruction<MyClass> ignored = mockConstruction(MyClass.class, 
         (mock, context) -> { when(new MyClass(any())).thenThrow(new MyException("fail"));})
) {
      stuffToTest();
  }

I've also tried the suggested solution here but it doesn't work.

Neets
  • 4,094
  • 10
  • 34
  • 46
  • What code are you trying to test? How is the constructed object used in `stuffToTest` method? – Jonasz Jan 26 '23 at 17:59
  • It's not really relevant -the important thing is that it constructs an instance of MyClass and that the constructor should throw an exception when called. This is possible with PowerMock but I can't find a way to do it with Mockito Inline, which is supposed to be a newer and nicer alternative – Neets Jan 27 '23 at 10:40
  • 1
    It is relevant because of how `mockito-inline` works and how it handles mocking static methods and objects construction. It is not just a copy of the way PowerMock work(ed). – Jonasz Jan 27 '23 at 11:18
  • Then let's just say I'm trying to test void stuffToTest() { new MyClass("hello"); } – Neets Jan 27 '23 at 15:33

0 Answers0