ようなものになるだろう。
あなたは、コンストラクタ
public class ClassUnderTest {
String name;
boolean condition;
public ClassUnderTest(String name, boolean condition) {
this.name = name;
this.condition = condition;
init();
}
...
}
そして、我々はできるテストクラスでコンストラクタ
public class MyClass {
public MyClass() { }
public void createCUTInstance() {
// ...
ClassUnderTest cut = new ClassUnderTest("abc", true);
// ...
}
...
}
ことを呼び出し、別のクラスでClassUnderTestを持っていると言います...
(1)PowerMockRunnerを使用しPrepareForTest注釈上記両方のターゲットクラスを引用:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ClassUnderTest.class, MyClass.class })
public class TestClass {
(2)モックオブジェクトを返すためのコンストラクタインターセプト:
@Before
public void setup() {
ClassUnderTest cutMock = Mockito.mock(ClassUnderTest.class);
PowerMockito.whenNew(ClassUnderTest.class)
.withArguments(Matchers.anyString(), Matchers.anyBoolean())
.thenReturn(cutMock);
}
(3)検証をコンストラクタ呼び出し:
@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);
}
私は、コンストラクタを呼び出さないとオブジェクトを取得できません。それは言語機能です。 –
あなたは何を意味するのかを説明してください – java123999
実際にテストしようとしていることを記述して、コンストラクタをモックする必要があると考えさせました。本当の必要がなければ私は驚かないだろう。 –