我正在测试我的JSF应用程序(v2.2.14),但是我遇到了一些困难,因为我无法模拟uiviewiewroot类。当我尝试使用Mockito嘲笑此课时,我会收到错误
java.lang.ExceptionInInitializerError
...
...
caused by java.util.MissingResourceException: Can't find javax.faces.LogStrings bundle
我使用ViewRoot来管理应用程序的java.util.locale,有时我需要阅读此信息。
我可以以哪种方式嘲笑此类以继续我的测试用例?
谢谢!
目前我包装了我可以轻松模拟的类中JSF的所有代码。
@Component
public class FacesComponent implements Serializable {
public Locale getLocaleFromFrontend() {
return FacesContext.getCurrentInstance().getViewRoot().getLocale();
}
}
,然后我的测试课与此类似
@Autowired
@InjectMocks
private LocalDateConverter localDateConverter;
@Autowired
@Spy
private FacesComponent facesComponent;
...
...
MockitoAnnotations.initMocks(this);
Mockito.doReturn(null).when(facesComponent).getLocaleFromFrontend();
如果您使用powermockito,则可以使用@suppressstaticinitialization来删除静态初始化器。https://github.com/powermock/powermock/wiki/suppressunwantedbehavior
例如,如果代码为:
import java.util.Locale;
import javax.faces.context.FacesContext;
public class TestedClass
{
public Locale getLocale()
{
return FacesContext.getCurrentInstance().getViewRoot().getLocale();
}
}
以下测试将通过(Javaee7,PowerMockito 1.6.4):
@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor({"javax.faces.component.UIViewRoot", "javax.faces.component.UIComponent", "javax.faces.component.UIComponentBase"})
@PrepareForTest({TestedClass.class, FacesContext.class, UIViewRoot.class, UIComponentBase.class, UIComponent.class, Locale.class})
public class TestedClassTest {
private final FacesContext facesContext = Mockito.mock(FacesContext.class);
private final UIViewRoot uiViewRoot = Mockito.mock(UIViewRoot.class);
private final Locale locale = PowerMockito.mock(Locale.class);
private final TestedClass instance = new TestedClass();
@Before
public void setUp() {
PowerMockito.mockStatic(FacesContext.class);
Mockito.when(FacesContext.getCurrentInstance()).thenReturn(facesContext);
Mockito.when(facesContext.getViewRoot()).thenReturn(uiViewRoot);
Mockito.when(uiViewRoot.getLocale()).thenReturn(locale);
}
/**
* Test of getLocale method, of class TestedClass.
*/
@Test
public void testGetLocale() {
assertEquals(locale, instance.getLocale());
}
}
确保您也抑制了Uiviewiewroot的超级类。