我有以下Logger我想模拟,但验证日志条目被调用,而不是内容.
private static Logger logger =
LoggerFactory.getLogger(GoodbyeController.class);
Run Code Online (Sandbox Code Playgroud)
我想模拟用于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));
...
}
Run Code Online (Sandbox Code Playgroud)
我想知道:
LoggerFactory.getLogger()以适用于任何类吗?when(loggerMock.isDebugEnabled()).thenReturn(true);的@Before,因此我似乎无法改变每个方法的特点.有没有解决的办法?编辑发现:
我以为我已经尝试了这个并且它没有用:
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
Run Code Online (Sandbox Code Playgroud)
但是,谢谢你,因为它确实有效.
但是我尝试了无数的变化:
when(loggerMock.isDebugEnabled()).thenReturn(true);
Run Code Online (Sandbox Code Playgroud)
我不能让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!";
}
...
}
Run Code Online (Sandbox Code Playgroud)
然后我有这个测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class ExampleServiceTests {
@Mock
private Logger loggerMock;
private ExampleServiceservice = new ExampleService();
@Before
public …Run Code Online (Sandbox Code Playgroud)