如何在Java / Swing中测试一个带有“ActionEvent”类型参数的函数?以下是我要测试的功能:
public void actionPerformed(ActionEvent e)
{
// Communicating with the Model class //
/** if the "Add" button has been pressed **/
if (e.getActionCommand() == "Add")
{
String cust_name = view.getAddCustNameField().getText();
int ph_num = Integer.parseInt(view.getAddPhoneNumField().getText());
model.addEntry(cust_name, ph_num, "controller");
}
/** if the "Delete" button has been pressed **/
else if (e.getActionCommand() == "Delete")
{
String cust_name = view.getDelCustNameField().getText();
model.deleteEntry(cust_name, "controller");
}
/** if the "Update" button has been pressed **/
else if (e.getActionCommand() == "Update")
{
String cust_name = view.getUpdCustNameField().getText();
int ph_num = Integer.parseInt(view.getUpdPhoneNumField().getText());
model.updateEntry(cust_name, ph_num, "controller");
}
// Communicating with the View class //
else
{
/** if the "Change Family" button has been pressed **/
Font fontRes = view.getResDisplayField().getFont();
Font fontDir = view.getDirDisplayField().getFont();
if (e.getActionCommand() == "Change Family")
{
String fontFamily = view.getFontFamilyField().getText();
if (fontFamily != "")
{
view.getResDisplayField().setFont(new Font(fontFamily, fontDir.getStyle(), fontRes.getSize()));
}
}
/** if the "Change Size" button has been pressed **/
else if (e.getActionCommand() == "Change Size")
{
int fontWeight = Integer.parseInt(view.getFontSizeField().getText());
if (fontWeight > 0)
{
view.getResDisplayField().setFont(new Font(fontRes.getFamily(), fontRes.getStyle(), fontWeight));
view.getDirDisplayField().setFont(new Font(fontDir.getFamily(), fontDir.getStyle(), fontWeight));
}
}
/** if the "Change Italics" button has been pressed **/
else if (e.getActionCommand() == "Change Style")
{
String fontStyle = (String)(view.getFontStyleCombo().getSelectedItem());
if (fontStyle == "Plain")
{
view.getResDisplayField().setFont(new Font(fontRes.getFamily(), Font.PLAIN, fontRes.getSize()));
view.getDirDisplayField().setFont(new Font(fontDir.getFamily(), Font.PLAIN, fontDir.getSize()));
}
else if (fontStyle == "Italic")
{
view.getResDisplayField().setFont(new Font(fontRes.getFamily(), Font.ITALIC, fontRes.getSize()));
view.getDirDisplayField().setFont(new Font(fontDir.getFamily(), Font.ITALIC, fontDir.getSize()));
}
else if (fontStyle == "Bold")
{
view.getResDisplayField().setFont(new Font(fontRes.getFamily(), Font.BOLD, fontRes.getSize()));
view.getDirDisplayField().setFont(new Font(fontDir.getFamily(), Font.BOLD, fontDir.getSize()));
}
}
}// 'else' (if the command is meant for the view class)
所以,基本上我想模仿按钮按下动作,并且根据按下的特定按钮,执行条件语句的一个分支。 对应每个按钮,有一组2个JTextField,其值必须以某种方式在我的单元测试函数中设置。那些是“... CustNameField”和“... PhoneNumField”的值,我在上面的函数中输入,所以我必须事先设置它们的值,以便我可以直接输入它们。我怎么能这样做?
答案 0 :(得分:0)
您可以使用像easymock或mokito这样的模拟框架。
这些框架可以让您: