我正在尝试编写测试,以检查是否已记录了某些行。我谷歌搜索了一段时间,但我无法弄清楚为什么不替换LOG
。
测试课程:
public class Example {
private static final Logger LOG = LoggerFactory.getLogger(Example.class);
public void foo(...)
{
if(...)
LOG.warn("Warning");
//...
}
}
测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyTest
{
@Mock
Logger logger;
@InjectMocks
private final Example example = new Example();
@Test
public void test1() {
PowerMockito.mockStatic(LoggerFactory.class);
logger = PowerMockito.mock(Logger.class);
PowerMockito.when(LoggerFactory.getLogger(Example.class)).thenReturn(logger);
example.foo(...);
Mockito.verify(logger).warn("Warning");
}
}
使用SLF4J,PowerMock 1.7.1。
ps:在此项目中替换private static final Logger LOG
是没有选项。
您为时过早创建了主题。您在创建主题后安排模拟井。
安排静态模拟后创建主题
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyTest {
@Test
public void test1() {
//Arrange
Logger logger = PowerMockito.mock(Logger.class);
PowerMockito.mockStatic(LoggerFactory.class);
PowerMockito.when(LoggerFactory.getLogger(Example.class)).thenReturn(logger);
Example example = new Example();
//Act
example.foo(..);
//Assert
Mockito.verify(logger).warn("Warning");
}
}