3

For example I have the following handler:

@Component
public class MyHandler {

  @AutoWired
  private MyDependency myDependency;

  public void someMethod(Object parameter) {
    ...
    ThirdPartyClass thirdPartyObject = new ThirdPartyClass(parameter);
    thirdPartyObject.unnecessaryMethod();
    ...
  }
}

To test this, I want to write something like this:

@RunWith(MockitoJUnitRunner.class}
class MyHandlerTest {

  @InjectMocks
  MyHandler myHandler;

  @Mock
  MyDependency myDependency;

  @Test
  public void testSomeMethod() {
    ...
    myHandler.someMethor(parameter);
    ...
  }
}

I want to avoid calling unnecessaryMethod(). Is there any way to do this?

If unnecessaryMethod() is static then I can use PowerMockito to mock it, but can PowerMockito help in my situation?

Juliën
  • 9,047
  • 7
  • 49
  • 80
Vova Yatsyk
  • 3,245
  • 3
  • 20
  • 34
  • Yes, PowerMockito can mock `new`-ed objects as well, using the `whenNew(...)` method; check the PowerMock documentation. – Rogério Jun 11 '15 at 17:14

1 Answers1

0

I have found an answer:

public class MyHandler {
    public void someMethod() {
        Utils utils = new Utils(10);
        System.out.println("Should be 1 : " + utils.someMethod());
    }
}

Some Utils class:

public class Utils {
    private int value = 5;
    Utils () {
        System.out.println("Should be mocked");
    }
    Utils (int param) {
        this.value = param;
        System.out.println("Should be mocked");
    }
    public int someMethod() {
        System.out.println("Should be mocked");
        return value;
    }
}

And test class:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyHandler.class)
public class MyHandlerTest {
    @InjectMocks
    MyHandler myHandler;
    @Test
    public void testMain() throws Exception {
        Utils utils = mock(Utils.class);
        when(utils.someMethod()).thenReturn(1);
        whenNew(Utils.class).withArguments(anyInt()).thenReturn(utils);
        myHandler.someMethod();
    }
}

Console output will be: Should be 1 : 1

Related question

Community
  • 1
  • 1
Vova Yatsyk
  • 3,245
  • 3
  • 20
  • 34