[英]PowerMockito mocking static class INSIDE enum?
我有一個枚舉,它必須有一個用於 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,而是嘲笑靜態內部類。 經過大量搜索,我嘗試了各種方法。 設置似乎正確,但可能會遺漏一些技巧。 有幫助嗎?
有點猜測: Category.class
是您打算測試的類。 該類本身不包含任何需要模擬/准備的內容。 所以:在你的代碼中刪除這些部分。 即使它不會導致您當前的問題,我很確定當您稍后開始測試時,它可能會產生各種不良后果。
除此之外,真正的答案是首先避免使用 PowerMock(ito)。 您已經在使用@Autowired,這意味着您正在使用 DI 框架。 大多數 DI 框架也有用於單元測試的鈎子。 所以你應該嘗試讓 @Autowired 在你的測試設置中工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.