モックアウトしたい次のロガーがありますが、ログエントリが呼び出されていることを検証するために、コンテンツに対してではありません。
private static Logger logger =
LoggerFactory.getLogger(GoodbyeController.class);
LoggerFactory.getLogger()に使用されるクラスをモックしたいのですが、その方法がわかりませんでした。これは私がこれまでに終わったものです:
@Before
public void performBeforeEachTest() {
PowerMockito.mockStatic(LoggerFactory.class);
when(LoggerFactory.getLogger(GoodbyeController.class)).
thenReturn(loggerMock);
when(loggerMock.isDebugEnabled()).thenReturn(true);
doNothing().when(loggerMock).error(any(String.class));
...
}
私が知りたいのですが:
- スタティックをモックし
LoggerFactory.getLogger()
てどのクラスでも機能させることはできますか? - でしか走れないように見えるので
when(loggerMock.isDebugEnabled()).thenReturn(true);
、@Before
メソッドごとに特性を変えることはできないようです。これを回避する方法はありますか?
調査結果の編集:
私はこれをすでに試したと思いましたが、うまくいきませんでした:
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
しかし、それがうまくいったので、ありがとう。
しかし、私は無数のバリエーションを試しました:
when(loggerMock.isDebugEnabled()).thenReturn(true);
loggerMockの動作を外部で変更することはできませんが、@Before
これはCoburturaでのみ発生します。Cloverを使用すると、カバレッジは100%を示しますが、どちらの方法でもまだ問題があります。
私はこの単純なクラスを持っています:
public ExampleService{
private static final Logger logger =
LoggerFactory.getLogger(ExampleService.class);
public String getMessage() {
if(logger.isDebugEnabled()){
logger.debug("isDebugEnabled");
logger.debug("isDebugEnabled");
}
return "Hello world!";
}
...
}
それから私はこのテストをします:
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class ExampleServiceTests {
@Mock
private Logger loggerMock;
private ExampleServiceservice = new ExampleService();
@Before
public void performBeforeEachTest() {
PowerMockito.mockStatic(LoggerFactory.class);
when(LoggerFactory.getLogger(any(Class.class))).
thenReturn(loggerMock);
//PowerMockito.verifyStatic(); // fails
}
@Test
public void testIsDebugEnabled_True() throws Exception {
when(loggerMock.isDebugEnabled()).thenReturn(true);
doNothing().when(loggerMock).debug(any(String.class));
assertThat(service.getMessage(), is("Hello null: 0"));
//verify(loggerMock, atLeast(1)).isDebugEnabled(); // fails
}
@Test
public void testIsDebugEnabled_False() throws Exception {
when(loggerMock.isDebugEnabled()).thenReturn(false);
doNothing().when(loggerMock).debug(any(String.class));
assertThat(service.getMessage(), is("Hello null: 0"));
//verify(loggerMock, atLeast(1)).isDebugEnabled(); // fails
}
}
クローバーでは、if(logger.isDebugEnabled()){
ブロックを100%カバーしています。しかし、私が検証しようとするとloggerMock
:
verify(loggerMock, atLeast(1)).isDebugEnabled();
インタラクションはゼロです。私も試しPowerMockito.verifyStatic()
ました; で@Before
しかしそれはまたゼロの相互作用を持っています。
これは、Coberturaがif(logger.isDebugEnabled()){
100%完全ではないことを示しているのは奇妙に思えますが、Cloverはそうしていますが、どちらも検証が失敗することに同意しています。