下面是我试图测试的代码,但在entityManager.find上获取空指针异常coz entityManager = null。有什么建议吗?
@Name("UserProfileConverter")
@BypassInterceptors
@Converter(forClass= UserProfile.class)
public class UserProfileConverter implements javax.faces.convert.Converter {
@Logger
private static Log logger;
public Object getAsObject(FacesContext arg0, UIComponent uiComponent, String s) {
EntityManager entityManager = (EntityManager) Component.getInstance("entityManager");
UserProfile p;
if(s == null || s.equals("null")) {
return null;
} else {
try {
long i = Long.parseLong(s);
return entityManager.find(UserProfile.class, i);
} catch (NumberFormatException e) {
logger.error(e);
} catch (SecurityException e) {
logger.error(e);
}
}
return null;
}
public String getAsString(FacesContext context, UIComponent uiComponetn, Object arg2) {
return ((CsaRole)arg2).getCsaRoleId() + "";
}
}
这是我的测试课..
public class UserProfileConverterTest extends SeamTest {
private UserProfileConverter converter;
private FacesContext mockFacesContext;
private UIComponent mockUiComponent;
private final static Logger logger = Logger.getLogger(UserProfileConverterTest.class);
@BeforeClass
public void setup() {
converter = new UserProfileConverter();
}
@Test
public void testGetAsObject()
throws Exception {
new ComponentTest() {
@Override
protected void testComponents() throws Exception {
String value = "11111111111";
converter.getAsObject(mockFacesContext, mockUiComponent, value);
}
}.run();
}
}
答案 0 :(得分:0)
公共类UserProfileConverterTest扩展了SeamTest {
EntityManager mockEntityManager; private UserProfileConverter converter; UIComponent mockUiComponent = null; MockFacesContext mockFacesContext = null; @BeforeClass public void setup() { converter = new CsaUserProfileConverter(); mockEntityManager = EasyMock.createMock(EntityManager.class); } class BaseComponentTest extends ComponentTest { protected void testComponents() throws Exception { ScopeType.EVENT.getContext().set("entityManager", mockEntityManager); } } @Test public void testGetAsObject() throws Exception { new BaseComponentTest() { protected void testComponents() throws Exception { super.testComponents(); UserProfile expectedResult = new UserProfile(); EasyMock.expect(mockEntityManager.find(UserProfile.class,1L)).andReturn(expectedResult); //Replay Mock EasyMock.replay(mockEntityManager); Object target = converter.getAsObject(mockFacesContext,mockUiComponent,"1"); Assert.assertEquals(expectedResult, target); //Verify the Mock EasyMock.verify(mockEntityManager); } }.run(); }