How to mock forName() method of Class class.

2,916 views
Skip to first unread message

Ishant

unread,
Oct 27, 2011, 6:29:01 AM10/27/11
to PowerMock
Hi,

I want to test the fun() method mocking the forName method of Class
class but i am getting exception when I am setting up the mock.

Here is the code

class A
{
public void fun()
{
Class<?> retcls;
retcls=Class.forName("some String");
.
.
}
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(Class.class)
class ATest
{
@Test
public testfun()
{
mockStatic(Class.class);
Class retclsMock =PowerMock.createMock(Class.class); //getting
exception in this statement


...

}
}


Need help in mocking the forName() method.

Thanks,
Ishant

Johan Haleby

unread,
Oct 27, 2011, 7:00:14 AM10/27/11
to powe...@googlegroups.com
Hi, 

I would advice strongly against mocking anything in the Class class. I've worked quite intensively with reflection over the years and I've never had the need to mock Class.forName(..). I suspect that there's another way to test what needs to be tested in your case. 

If you still feel that you need to mock the method you have to use this approach. But since it's Class.forName(..) there's a big chance that you'll screw things up for other frameworks including PowerMock (which makes heavy use of reflection itself). But you could of course give it a try...

/Johan


--
You received this message because you are subscribed to the Google Groups "PowerMock" group.
To post to this group, send email to powe...@googlegroups.com.
To unsubscribe from this group, send email to powermock+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/powermock?hl=en.


Reply all
Reply to author
Forward
0 new messages