M Sach M Sach - 2 years ago 143
Java Question

Java How to mock the object and static method in java?

I am writing a junit of CustomerHelper which internally calls the method of AccountHelper object. The CustomerHelper is creating the
AccountHelper object with new operator inside one of its method. Now if i want to mock the AccountHelper object.Is there any way i can do it?

If this dependency (AccountHelper in this case) would have been injected by some setter or constructor, i could have set my MockAccountHelper.Right?
But is there any way we can do mocking when we are creating dependency with New operator?

Second question:- Is there anyway we can mock static methods using core java library without going for Power/Easy Mock?Even if i go power mocks , want to understand how it is doing it internally in brief?

Answer Source

JMockit allows you to easily mock static methods and internally-constructed objects.

You'd do something like this:

public void testWhatever() {
    new Expectations() {
        AccountHelper accountHelper;
            new AccountHelper();

I don't believe there is a built-in way to mock static methods in the core Java library. I'm also not sure exactly what happens internally, but I think that JMockit does some kind of bytecode-level tinkering to replace classes on the fly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download