all-powerMock/PowerMockitoを使用して嘲笑しています。whenNewまたはexpectNewが実際のコンストラクタを呼び出していないときに黙って
ここでは、Spring用の新しいコンストラクタを呼び出すクラスを示します。
public class BaseService {
private void loadSpringConfig(String customResourceName) {
String[] resources = new String[1];
resources[0] = "test.xml";
context = new ClassPathXmlApplicationContext(resources);
}
}
ここで私が嘲笑に使用しているコードです。 weHnNewとexpectNewを使用すると、 'ClassPathXmlApplicationContext'コンストラクタが呼び出され、ファイルが見つからないという例外が発生します。 がが新しい呼び出しを避ける:答えはとても単純なことができPowerMock暗黒の力...に
@RunWith(PowerMockRunner.class)
@PrepareForTest({BaseService.class,
ClassPathXmlApplicationContext.class})
public class BaseServiceTest {
@Mock
ClassPathXmlApplicationContext ctx;
@Test
public void loadSpringConfigTest() throws Exception{
//ClassPathXmlApplicationContext ctx = PowerMockito.mock(ClassPathXmlApplicationContext.class);
Method method;
String[] resources = new String[1];
resources[0]="test.xml";
BaseService bs = new BaseService();
try {
method = BaseService.class.getDeclaredMethod("loadSpringConfig",String.class);
method.setAccessible(true);
//trowing exception of file not found - tried various option with no luck
PowerMockito.whenNew(ClassPathXmlApplicationContext.class).withAnyArguments().thenReturn(ctx);
//Other tries
//withParameterTypes(String[].class).withArguments(resources).thenReturn(ctx);
//PowerMock.expectNew(ClassPathXmlApplicationContext.class,new Class[]{String[].class},resources).andReturn(ctx);
method.invoke(bs,"test");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PowerMockのどのバージョンを使用していますか? –
こんにちはAurthur、私はpowermock-core-1.6.2を使用しています。 –
私の場合、すべての機能は見た目がよく、ただし、リフレクションを使用して呼び出されます。しかし、それは影響を与えるべきではありません。私は調査します。 –