PowerMock, Mockito, TestNG with final classes and static methods

537 views
Skip to first unread message

bdusauso

unread,
Oct 21, 2011, 10:23:25 AM10/21/11
to PowerMock
Hi,

Nearly everything is in the title.
I've already search the documentation and the web but, as you've
guessed it, found nothing.
That's why I'm asking here.

I'm trying to mock a final class having a static method (which is
called).
I'm using PowerMock 1.4.10 with Mockito and TestNG.

Here's the kind of things I'm trying to do.
It's not the real project but it reproduces exactly what I'm trying to
do :

@ContextConfiguration(locations = {"classpath:application-context-
test.xml"})
@PrepareForTest(Misc.class)
public class UserDaoImplTest extends AbstractTestNGSpringContextTests
{

@Autowired
private UserDao userDao;

@Test
public void testPersist() {
mockStatic(Misc.class);
when(Misc.dummyMethod()).thenReturn(true);

User user = new User();
user.setFirstName("Bruno");
user.setLastName("Dusausoy");

userDao.persist(user);
}
}

My UserDao calls Misc.dummyMethod() and thus it is what I'm trying to
mock.

I've found the way to do it with JUnit, thanks to the rule, but
unfortunately I'm stuck with TestNG, at least on a bunch of specific
projects.

Any pointers ?

Regards.

Johan Haleby

unread,
Oct 24, 2011, 2:26:29 AM10/24/11
to powe...@googlegroups.com
Hi, 

You could try using the Java Agent Rule in TestNG and see if it works (bugs are known to exist though).

/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.


Brice Dutheil

unread,
Oct 24, 2011, 5:04:04 AM10/24/11
to powe...@googlegroups.com
Hi,

If you are using spring why don't refactor this static method as an instance dependency ?
If the Misc.dummyMethod is legacy, you can still do that by wrapping it in a Object that will be injected.

I know it doesn't answer your question but I find this design much better for the long run.



-- 
Brice
Reply all
Reply to author
Forward
0 new messages