我正在为我的bean编写组件测试,因为来自addMessage()
的{{1}}方法,我不断获得NullPointerExceptions。
我确定这是因为FacesContext
方法,因为如果我删除测试通过的行。如何模拟addMessage()
方法?
TrendBean
addMessage()
TrendBeanTest
@Named(value = "trendBean")
@ViewScoped
@SuppressWarnings("deprecation")
public class TrendBean extends AbstractBean implements Serializable {
private static final long serialVersionUID = -310401000218411384L;
private static final Logger logger = Logger.getLogger(TrendBean.class);
private ChartPoint point;
private List<ChartPoint> points;
@Inject
private ITrendManager manager;
public String addChartPoint() {
if (!isLoggedIn()) {
return null;
}
assertNotNull(point);
final User user = getSession().getUser();
manager.addPointToUser(user, point);
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_INFO,
getTranslation("pointAdded"), ""));
init();
return null;
}
}
AbstractBean
public class TrendBeanTest {
@Tested
TrendBean trendBean;
@Injectable
LoginBean loginBean;
@Injectable
Session session;
@Injectable
ITrendManager manager;
@Injectable
IUserManager userManager;
@Injectable
User user;
@Test
public void testAddChartPoint(@Mocked FacesContext fakeContext) {
new NonStrictExpectations() {
{
session.isLoggedIn();
result = true;
session.getUser();
result = user;
manager.addPointToUser((User) any, (ChartPoint) any);
FacesContext.getInstance();
result = fakeContext;
};
};
Deencapsulation.setField(trendBean, "point", new ChartPoint());
assertEquals(null, trendBean.addChartPoint());
}
}
答案 0 :(得分:0)
在这种情况下,在FacesContext.getCurrentInstance().addMessage
的调用内部,您也调用AbstractBean .getTranslation(String)
,您还需要模拟该方法。
这样的事情:
<强> TrendBeanTest 强>
public class TrendBeanTest {
@Tested
TrendBean trendBean;
@Injectable
LoginBean loginBean;
@Injectable
Session session;
@Injectable
ITrendManager manager;
@Injectable
IUserManager userManager;
@Injectable
User user;
@Test
public void testAddChartPoint(@Mocked FacesContext fakeContext, @Mocked AbstractBean abstractBean) {
new NonStrictExpectations() {
{
session.isLoggedIn();
result = true;
session.getUser();
result = user;
manager.addPointToUser((User) any, (ChartPoint) any);
FacesContext.getInstance();
result = fakeContext;
abstractBean.getMessage(anyString); result = "foo";
};
};
Deencapsulation.setField(trendBean, "point", new ChartPoint());
assertEquals(null, trendBean.addChartPoint());
new Verifications(){{
fakeContext.addMessage(withNull(), (FacesMessage)any);
}};
}
}
注意:我是在没有IDE的情况下从头开始做的,所以也许我已经改写了一些东西。