Twilite:
私はその方法の一つにローカル内部クラスを持つクラスを持っています:
public class Outer {
String hello = "hello";
public void myMethod() {
class Inner {
public void myInnerMethod() {
System.out.println(hello);
}
}
[...really slow routine...]
(new Inner()).myInnerMethod();
}
}
私がテストしたいと思いますmyInnerMethod()
。だから私は、リフレクションを使用してローカル内部クラスをインスタンス化して呼び出すmyInnerMethod()
ことに。
public void test() {
Object inner = Class.forName("Outer$Inner").newInstance();
inner.getClass().getDeclaredMethod("myInnerMethod").invoke(inner); // hello will be null
}
ときでもmyInnerMethod()
アクセスするhello
外部クラスのスコープ内にある、それはありますnull
。
モックまたはそれ以外に挨拶を提供する方法はありますかmyInnerMethod()
?
私は内部クラスを抽出することで、私のコードをリファクタリングまたはちょうど外のパブリックメソッドをテストすることができ知っています。しかし、それを行う方法はまだありますか?
マチェイコワルスキー:
あなたは、内部動作を確認できるようになる前に、いくつかの小さなリファクタリングを行う必要があります:
1)内から呼び出されたコードを含むであろうパッケージレベルのメソッドを作成myInnerMEthod
。
public class Outer {
String hello = "hello";
public void myMethod() {
class Inner {
public void myInnerMethod() {
Outer.this.printHello(hello); // !!! change here
}
}
[...really slow routine...]
(new Inner()).myInnerMethod();
}
void printHello(String hello){/* */} // !! add this
}
2)上のスパイOuter
クラスとベリファイprintHello
ハローインスタンス変数と呼ばれています。
public void test() {
// Arrange
Outer outerSpy = spy(new Outer());
doNothing().when(outerSpy).printHello(anyString()); // optional
// Act
outer.myMethod();
// Assert
verify(outerSpy).printHello("hello");
}