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)
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)
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.
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 =]
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.