Bur*_*man 2 java unit-testing mockito powermock
我有一个实用程序类,它是最后一堂课。在那里,我使用注入来注入LOGGER。
public final class Utilities {
@Inject
private static Logger.ALogger LOGGER;
private Utilities() {
//this is the default constructor. so there is no implementation
}
public static String convertToURl(string input){
try{
//do some job
}catch(IllegalArgumentException ex){
LOGGER.error("Invalid Format", ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我为此方法编写单元测试时,我必须模拟LOGGER,否则它将抛出空指针异常。我如何在不创建此类实例的情况下模拟此LOGGER。我试图将变量白名单化。但这仅适用于实例吗?
此代码可以正常工作。要设置静态字段,您需要将类传递给org.powermock.reflect.Whitebox.setInternalState。请确保使用软件包中的PowerMock的类,org.powermock.reflect因为Mockito的类具有相同的名称。
@RunWith(PowerMockRunner.class)
public class UtilitiesTest {
@Mock
private Logger.ALogger aLogger;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this); // for case them used another runner
Whitebox.setInternalState(CcpProcessorUtilities.class, "LOGGER", aLogger);
}
@Test
public void testLogger() throws Exception {
Utilities.convertToURl("");
verify(aLogger).error(eq("Invalid Format"), any(IllegalArgumentException.class));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8377 次 |
| 最近记录: |