0

I am trying to Unit Test a class in Java.

Code for this class: ToBeTested

public class ToBeTested {
    private Collaborator collaborator;

    public ToBeTested() {
        System.out.println("ToBeTested: Constructor");
    }

    public void start() {
        System.out.println("ToBeTested: Start");
        collaborator = new Collaborator();
    }
}

This class ToBeTested depends on another class, Collaborator.

Code for class: Collaborator

public class Collaborator {

    Collaborator() {
        System.out.println("Collaborator: Constructor");
    }
}

While testing the class ToBeTested, I want to stub instantiation of Collaborator. That's a dependency I want to mock and I don't want it's constructor to be called.

I'm using Junit (v4.12) and PowerMock (v1.6.1).

Code for Test Class: TestToBeTested

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.powermock.api.easymock.PowerMock.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ToBeTested.class, Collaborator.class})
public class TestToBeTested {

    @Mock
    private Collaborator collaborator;

    private ToBeTested toBeTested;

    @Before
    public void setUp() throws Exception {
        collaborator = createMock(Collaborator.class);
        expectNew(collaborator.getClass()).andReturn(null);
        toBeTested = new ToBeTested();
    }

    @Test
    public void test() {
        replayAll();

        toBeTested.start();

        verifyAll();
    }

}

My understanding is that this will mock or stub out Collaborator and it's constructor should not be called. However, when I run the test, I notice that original constructor of Collaborator is called.

Output of test run:

ToBeTested: Constructor
ToBeTested: Start
Collaborator: Constructor

I'm very new to Java and Unit Testing in Java, so I apologize if I'm doing a very fundamental mistake here.

During my quest to find out the root cause, I have referred to following SO questions:

Thank you very much in advance for help/suggestions/feedback.

Neeraj Sharma
  • 1,067
  • 7
  • 14

1 Answers1

0

One possible reason that it might not be working could be this line:

expectNew(collaborator.getClass()).andReturn(null);

collaborator is a mocked instance which means it's "getClass()" method is going to return Collaborator$CGLIBMockedWithPowermock or something like that -- not the Collaborator class you want it to be. So you might get it to work simply by changing that line to:

expectNew(Collaborator.class).andReturn(null);
goolie
  • 145
  • 1
  • 7