【发布时间】:2018-09-13 18:58:44
【问题描述】:
我有一个枚举,它必须有一个用于 bean 注入的内部静态类。
我觉得我正面临模拟最困难的情况:枚举、静态类、静态字段、静态方法..
public enum Category{
C1(Something(Constants.getFactory().createSomething(""))),
C2(...);
public static Constants {
@Autowired
private static Factory factory;
public static Factory getFactory(){
return factory;
}
}
}
而我使用 PowerMockito 的测试类是:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Category.class,Category.Constants.class})
public class CategoryTests {
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(Category.class);
PowerMockito.mockStatic(Category.Constants.class);
//This simply testing mock didn't work
//PowerMockito.when(Category.Constants
// .getFactory()).thenReturn("123");
//I tried to mock the inner field 'factory' and use it directly without a getter
//(with small changes in the original class)
//But it didn't work either
Factory factory = PowerMockito.mock(Factory.class);
NewClass newClass = PowerMockito.mock(NewClass.class);
PowerMockito.when(Factory.createSomething(anySring()))
.thenReturn(newClass);
Whitebox.setInternalState(
Category.Constants.class,"factory",Factory);
//This is like the most common way to stub
//It didn't work, so I believe the inner static class were never mocked
PowerMockito.doReturn(factory).when(Category.Constants.class,
"getFactory", anyString());
}
//I don't know if real test cases matter that much but I update to add it for reference.
@Test(dataProvider = "Case1")
public void testFromFilterType(final String testName, String input, final Category expected) {
assertEquals(Category.doSomething(input), expected);
}
@DataProvider(name = "Case1")
Object[][] fromFilterTypeCases() {
return new Object[][] {
{ "C1", "input1", Category.C1 },
{ "C2", "input2", Category.C2 },
};
}
}
//Currently the tests got skipped because in class Category Constants.getFactory().createSomething(""),
//where Constants.getFactory() returns null and mocking doesn't work.
起初我没有模拟 Enum,而只是模拟了静态内部类。经过大量搜索,我尝试了各种方式。设置似乎正确,但可能会错过一些技巧。有什么帮助吗?
【问题讨论】:
-
我认为这些模拟是在枚举初始化之后执行的。如何在枚举初始化之前模拟方法?
标签: java junit mockito powermock powermockito