powermock mocking constructor via whennew() does not work with anonymous class

后端 未结 4 631
不知归路
不知归路 2021-01-03 20:34

I have a DummyResource class and a DummyTarget file, and a test class TestDummyResource as below, but the mocked object DummyResource dr = mock(DummyResource.class)

相关标签:
4条回答
  • 2021-01-03 21:15

    Actually, you have to prepare for test the class that makes the constructor call, not the class on which the constructor was called. See https://github.com/jayway/powermock/wiki/MockConstructor.

    In your case, you should use @PrepareForTest(DummyTarget.class)

    0 讨论(0)
  • 2021-01-03 21:17

    It looks like an anonymous class may inherit the package of the class that defines it. Can you try the wildcard form of PrepareForTest?:

    @PrepareForTest("com.smin.dummy.*")
    

    If that doesn't work, you could try the shotgun PrepareEverythingForTest Annotation.

    0 讨论(0)
  • 2021-01-03 21:26

    I had the same problem, and resolved it with using whenNew with fully qualified name. The fully qualified name of an inner anonymous class in your case is:

    DummyTarget.class + "$1"
    

    so you should create a mock of that class:

    DummyResource dr = mock(Class.forName(DummyTarget.class + "$1"));
    

    and it will work for you.

    Also, don't forget to prepare the DummyTarget class:

    @PrepareForTest(DummyTarget.class)
    

    Hope it helped =]

    0 讨论(0)
  • 2021-01-03 21:27

    You need to have prepared the class calling the constructor, not the class on which the constructor is called, the following should fix you up:

    @PrepareForTest(DummyTarget.class)
    

    For more information check this page.

    0 讨论(0)
提交回复
热议问题