You can do it with Mockito and PowerMockito.
Say you have ClassUnderTest with a constructor
public class ClassUnderTest {
String name;
boolean condition;
public ClassUnderTest(String name, boolean condition) {
this.name = name;
this.condition = condition;
init();
}
...
}
And another class that calls that constructor
public class MyClass {
public MyClass() { }
public void createCUTInstance() {
// ...
ClassUnderTest cut = new ClassUnderTest("abc", true);
// ...
}
...
}
At the Test class we could...
(1) use PowerMockRunner and cite both target classes above in the PrepareForTest annotation:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ClassUnderTest.class, MyClass.class })
public class TestClass {
(2) intercept the constructor to return a mock object:
@Before
public void setup() {
ClassUnderTest cutMock = Mockito.mock(ClassUnderTest.class);
PowerMockito.whenNew(ClassUnderTest.class)
.withArguments(Matchers.anyString(), Matchers.anyBoolean())
.thenReturn(cutMock);
}
(3) validate the constructor call:
@Test
public void testMethod() {
// prepare
MyClasss myClass = new MyClass();
// execute
myClass.createCUTInstance();
// checks if the constructor has been called once and with the expected argument values:
String name = "abc";
String condition = true;
PowerMockito.verifyNew(ClassUnderTest.class).withArguments(name, condition);
}