我正在尝试编写检查是否已记录某些行的测试。我用谷歌搜索了一段时间,但我无法弄清楚为什么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
。
答案 0 :(得分:1)
您过早地创建主题。在创建主题后,您可以很好地安排模拟。
在安排静态模拟后创建主题
@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");
}
}