Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I use powermockito verifyNew?

Tags:

powermock

Having trouble with this. I've used Powermockito quite a bit in the past. Normally this is pretty smooth. I figured I'd post my problem rather than continue to rummage through examples. So the goal is to verify a call to new for a class. I don't think this is the most popular feature of powermockito. Here's the test:

import static org.powermock.api.mockito.PowerMockito.verifyNew;
import static org.powermock.api.mockito.PowerMockito.whenNew;

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUnderTest.class)
public class VerifyNewTest {

  ClassUnderTest myClassUnderTest = new ClassUnderTest();

  @Before
  public void setUp() throws Exception {
  }

  @Test
  public void test() throws Exception {
    whenNew(Collaborator.class).withNoArguments().thenReturn(new Collaborator());
    myClassUnderTest.doSomething();
    verifyNew(Collaborator.class).withNoArguments();
  }

}

and said classes

public class ClassUnderTest {

  public void doSomething() {
    new Collaborator();
  }
}


public class Collaborator {

}

My goal was to make this as simple as possible. I suppose I could have added some mock objects and stubbed some behavior. Anyway, I get.

org.mockito.exceptions.misusing.UnfinishedStubbingException:  Unfinished stubbing detected here:
    -> at org.powermock.api.mockito.internal.invocationcontrol. MockitoNewInvocationControl.expectSubstitutionLogic(MockitoNewInvocationControl.java:65)


E.g. thenReturn() may be missing. Examples of correct stubbing:

when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();

Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!

like image 548
Michael Sampson Avatar asked Feb 06 '14 17:02

Michael Sampson


1 Answers

Return a mock object in the whenNew() clause would work in your case.

@Test
public void test() throws Exception {
    whenNew(Collaborator.class).withNoArguments().thenReturn(mock(Collaborator.class));
    myClassUnderTest.doSomething();
    verifyNew(Collaborator.class).withNoArguments();
}
like image 92
thundear Avatar answered Sep 29 '22 21:09

thundear