使用PowerMock时避免使用wait()方法时出现IllegalMonitorStateException

时间:2014-12-15 19:37:46

标签: java tdd mockito powermock

我试图避免使用PowerMock进行wait()方法调用。我已尝试使用下面的代码,但没有成功(我是否关闭?)。有人可以帮忙吗?

@RunWith(PowerMockRunner.class)
@PrepareForTest(Bar.class)
public class MyTest {

    @Test
    public void test() throws InterruptedException{
        Foo foo = new Foo();
        Foo fooSpy = PowerMockito.spy(foo);

        Bar barMock = PowerMockito.mock(Bar.class);
        PowerMockito.doReturn(barMock).when(fooSpy).getBar();
        PowerMockito.doNothing().when(barMock).wait();

        fooSpy.makeBarWait();
    }
}

public class Bar{}

public class Foo {

    private Bar bar;

    public Bar getBar() {
        return bar;
    }

    public void makeBarWait() throws InterruptedException {
        // do something...
        synchronized (this) {               
            getBar().wait();
        }
    }
}

我猜这个方法仍然被调用,因为我收到了这个错误:

java.lang.IllegalMonitorStateException
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:503)

1 个答案:

答案 0 :(得分:1)

Your code为我抛出NullPointerException。你需要在你监视的对象上调用makeBarWait()

@Test
public void test() throws InterruptedException {
  Foo foo = new Foo();
  Foo fooSpy = PowerMockito.spy(foo);

  Bar barMock = PowerMockito.mock(Bar.class);
  PowerMockito.doReturn(barMock).when(fooSpy).getBar();
  PowerMockito.doNothing().when(barMock).wait();

  fooSpy.makeBarWait();  // <-----
}

然后测试通过我。