Java JMenuItem的单元测试

Java JMenuItem的单元测试,java,swing,junit,jmenuitem,actionevent,Java,Swing,Junit,Jmenuitem,Actionevent,我不熟悉JUnit测试。我正在尝试测试导出报表的方法。基本上,这个方法会弹出一个保存菜单来选择文件保存的位置,并从另一个类获取报告。我不知道我需要在这里测试什么,甚至不知道如何测试它。我还添加了我的JMenuItem和actionEvent。任何想法或帮助都会被接受 以下是我的建议: JMenuItem jMenuFileexportProjectReport = new JMenuItem(exportProjectReportAction); public Act

我不熟悉JUnit测试。我正在尝试测试导出报表的方法。基本上,这个方法会弹出一个保存菜单来选择文件保存的位置,并从另一个类获取报告。我不知道我需要在这里测试什么,甚至不知道如何测试它。我还添加了我的JMenuItem和actionEvent。任何想法或帮助都会被接受

以下是我的建议:

    JMenuItem jMenuFileexportProjectReport = new JMenuItem(exportProjectReportAction); 
        public Action exportProjectReportAction =
            new AbstractAction(Local.getString("Export Project Report")) {

            public void actionPerformed(ActionEvent e) {
                reportExportAction(e);
            }
    };
以下是JMenuItem的我的操作事件:

    JMenuItem jMenuFileexportProjectReport = new JMenuItem(exportProjectReportAction); 
        public Action exportProjectReportAction =
            new AbstractAction(Local.getString("Export Project Report")) {

            public void actionPerformed(ActionEvent e) {
                reportExportAction(e);
            }
    };
以下是我导出报告的方法:

public void reportExportAction(ActionEvent e) {

            JFileChooser chooser = new JFileChooser();
            chooser.setFileHidingEnabled(false);
            chooser.setDialogTitle(Local.getString("Export Project Report"));
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            chooser.addChoosableFileFilter(
                    new AllFilesFilter(AllFilesFilter.XHTML));
            chooser.addChoosableFileFilter(new AllFilesFilter(AllFilesFilter.HTML));

            String lastSel = (String) Context.get("LAST_SELECTED_EXPORT_FILE");
            if (lastSel != null) {
                    chooser.setCurrentDirectory(new File(lastSel));
            }

            ProjectExportDialog dlg =
                    new ProjectExportDialog(
                            App.getFrame(),
                            Local.getString("Export Project Report"),
                            chooser);

            String enc = (String) Context.get("EXPORT_FILE_ENCODING");
            if (enc != null) {
                    dlg.encCB.setSelectedItem(enc);
            }



            Dimension dlgSize = new Dimension(550, 500);
            dlg.setSize(dlgSize);
            Dimension frmSize = App.getFrame().getSize();
            Point loc = App.getFrame().getLocation();
            dlg.setLocation(
                    (frmSize.width - dlgSize.width) / 2 + loc.x,
                    (frmSize.height - dlgSize.height) / 2 + loc.y);
            dlg.setVisible(true);

            if (dlg.CANCELLED) {
                    return;
            }

                    Context.put(
                            "LAST_SELECTED_EXPORT_FILE",
                            chooser.getSelectedFile().getPath());

            int ei = dlg.encCB.getSelectedIndex();
            enc = null;
            if (ei == 1) {
                    enc = "UTF-8";
            }
            boolean nument = (ei == 2);
            File f = chooser.getSelectedFile();
            boolean xhtml =
                    chooser.getFileFilter().getDescription().indexOf("XHTML") > -1;
             CurrentProject.save();
             ReportExporter.export(CurrentProject.get(), chooser.getSelectedFile(), enc, xhtml, 
                              nument); 
            }
类创建HTML报告:

public class ReportExporter {

static boolean _chunked = false;
static boolean _num = false;
static boolean _xhtml = false;
static boolean _copyImages = false;
static File output = null;
static String _charset = null;
static boolean _titlesAsHeaders = false;
static boolean _navigation = false;

static String charsetString = "\n";




public static void export(Project prj, File f, String charset, boolean xhtml, boolean chunked) {


    _chunked = chunked;
    _charset = charset;
    _xhtml = xhtml;

    if (f.isDirectory()) {
        output = new File(f.getPath() + "/Project Report.html");
    }
    else {
        output = f;
    }

    NoteList nl = CurrentStorage.get().openNoteList(prj);
    Vector notes = (Vector) nl.getAllNotes(); 



   //Creates Labels for the HTML output for each section.
   String notesLabelHTML = "Notes";
   String tasksLabelHTML = "Tasks";
   String eventsLabHTML = "Events";


    //NotesVectorSorter.sort(notes);
    Collections.sort(notes);



    Writer fw;

    if (output.getName().indexOf(".htm") == -1) {
        String dir = output.getPath();
        String ext = ".html";

        String nfile = dir + ext;

        output = new File(nfile);
    }        
    try {
        if (charset != null) {
            fw = new OutputStreamWriter(new FileOutputStream(output),
                    charset);
            charsetString = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset="
                    + charset + "\" />";
        }
        else
            fw = new FileWriter(output);
    }
    catch (Exception ex) {
        new ExceptionDialog(ex, "Failed to write to " + output, "");
        return;
    }

    //Writes the title and the notes section of the HTMl Report
    write(fw, "<html>\n<head>\n" + charsetString + "<title>"
            + prj.getTitle()
            + "</title>\n</head>\n<body>\n<h1 class=\"projecttitle\">" 
            + prj.getTitle() +  "</h1>\n" +"\n<br>\n" 
            + "</title>\n</head>\n<body>\n<h2 class=\"projecttitle\">"
            + notesLabelHTML + "</h2>\n" );
    generateChunks(fw, notes);

    //Writes the Task section of the HTML Report
    write(fw, "\n<hr></hr><a" +"</title>\n</head>\n<body>\n<h2 class=\"projecttitle\">" + "\n<br>\n"
            + tasksLabelHTML + "</h2>\n" );

    //writes the Events section of the HTML Report
    write(fw, "\n<hr></hr><a" +"</title>\n</head>\n<body>\n<h2 class=\"projecttitle\">" + "\n<br>\n"
            + eventsLabHTML + "</h2>\n" );

    //Writes the ending of the report with the data and time
    write(fw, "\n<hr></hr><a "
            + "\n<br></br>\n" + new Date().toString()
            + "\n</body>\n</html>");
    try {
        fw.flush();
        fw.close();
    }
    catch (Exception ex) {
        new ExceptionDialog(ex, "Failed to write to " + output, "");
    }
}




public static String getNoteHTML(Note note) {
    String text = "";
    StringWriter sw = new StringWriter();
    AltHTMLWriter writer = new AltHTMLWriter(sw,
            (HTMLDocument) CurrentStorage.get().openNote(note), _charset,
            _num);
    try {
        writer.write();
        sw.flush();
        sw.close();
    }
    catch (Exception ex) {
        new ExceptionDialog(ex);
    }
    text = sw.toString();
    if (_xhtml) {
        text = HTMLFileExport.convertToXHTML(text);
    }

    text = Pattern
            .compile("<body(.*?)>", java.util.regex.Pattern.DOTALL
                    + java.util.regex.Pattern.CASE_INSENSITIVE).split(text)[1];
    text = Pattern
            .compile("</body>", java.util.regex.Pattern.DOTALL
                    + java.util.regex.Pattern.CASE_INSENSITIVE).split(text)[0];

    text = "<div class=\"note\">" + text + "</div>";

    if (_titlesAsHeaders) {
                    text = "\n\n<div class=\"date\">"
                + note.getDate().getFullDateString()
                + ":</div>\n<h1 class=\"title\">" + note.getTitle()
                + "</h1>\n" + text;
    }

    return text;
}


private static String generateNav(Note prev, Note next) {
    String s = "<hr></hr><div class=\"navigation\"><table border=\"0\" width=\"100%\" cellpadding=\"2\"><tr><td width=\"33%\">";
    if (prev != null)  {  
        s += "<div class=\"navitem\"><a href=\"" + prev.getId() + ".html\">"
                + Local.getString("Previous") + "</a><br></br>"
                + prev.getDate().getMediumDateString() + " "
                + prev.getTitle() + "</div>";
    }

    else {
        s += "&nbsp;";
            s += "</td><td width=\"34%\" align=\"center\"><a href=\""
            + output.getName()
            + "\">Up</a></td><td width=\"33%\" align=\"right\">";
    }

    if (next != null) {
        s += "<div class=\"navitem\"><a href=\"" + next.getId() + ".html\">"
                + Local.getString("Next") + "</a><br></br>"
                + next.getDate().getMediumDateString() + " "
                + next.getTitle() + "</div>";
    }

    else {
        s += "&nbsp;";
    }
    s += "</td></tr></table></div>\n";
    return s;
}



private static void generateChunks(Writer w, Vector notes) {
    Object[] n = notes.toArray();
    for (int i = 0; i < n.length; i++) {
        Note note = (Note) n[i];
        CalendarDate d = note.getDate();
        if (_chunked) {
            File f = new File(output.getParentFile().getPath() + "/"
                    + note.getId()
                    + ".html");
            Writer fw = null;
            try {
                if (_charset != null) {
                    fw = new OutputStreamWriter(new FileOutputStream(f),
                            _charset);
                }

                else {
                    fw = new FileWriter(f);
                }

                String s = "<html>\n<head>\n"+charsetString+"<title>" + note.getTitle()
                        + "</title>\n</head>\n<body>\n" + getNoteHTML(note);

                if (_navigation) {
                    Note nprev = null;
                    if (i > 0) {
                        nprev = (Note) n[i - 1];
                    }

                    Note nnext = null;
                    if (i < n.length - 1) {
                        nnext = (Note) n[i + 1];
                    }

                    s += generateNav(nprev, nnext);
                }
                s += "\n</body>\n</html>";
                fw.write(s);
                fw.flush();
                fw.close();
            }
            catch (Exception ex) {
                new ExceptionDialog(ex, "Failed to write to " + output, "");
            }
        }
        else {
            write(w, "<a name=\""  + "\">" + note.getDate() +"</a>\n" + getNoteHTML(note) + "</a>\n");
        }
    }
}


private static void write(Writer w, String s) {
    try {
        w.write(s);
    }
    catch (Exception ex) {
        new ExceptionDialog(ex, "Failed to write to " + output, "");
    }
}
公共类ReportExporter{
静态布尔值_chunked=false;
静态布尔值_num=false;
静态布尔值_xhtml=false;
静态布尔值_copyImages=false;
静态文件输出=null;
静态字符串_charset=null;
静态布尔值_titlesHeaders=false;
静态布尔导航=false;
静态字符串charsetString=“\n”;
公共静态void导出(项目prj、文件f、字符串字符集、布尔xhtml、布尔分块){
_分块=分块;
_字符集=字符集;
_xhtml=xhtml;
if(f.isDirectory()){
输出=新文件(f.getPath()+“/Project Report.html”);
}
否则{
输出=f;
}
NoteList nl=CurrentStorage.get().openNoteList(prj);
向量注释=(向量)nl.getAllNotes();
//为每个节的HTML输出创建标签。
字符串notesLabelHTML=“Notes”;
字符串tasksLabelHTML=“Tasks”;
字符串eventsLabHTML=“Events”;
//NotesVector分拣机。分拣(notes);
收藏。分类(注释);
作家fw;
if(output.getName().indexOf(“.htm”)=-1){
String dir=output.getPath();
字符串ext=“.html”;
字符串nfile=dir+ext;
输出=新文件(nfile);
}        
试一试{
if(字符集!=null){
fw=新的OutputStreamWriter(新文件输出流(输出),
字符集);
charsetString=“”;
}
其他的
fw=新文件写入程序(输出);
}
捕获(例外情况除外){
新的异常对话框(例如,“未能写入“+输出,”);
返回;
}
//编写HTMl报告的标题和注释部分
写入(fw),“\n\n”+charsetString+”
+prj.getTitle()
+“\n\n\n”
+prj.getTitle()+“\n”+“\n
\n” +“\n\n\n” +notesLabelHTML+“\n”); 发电机组(fw,注释); //写入HTML报告的任务部分 写(fw),“\n



” +prev.getDate().getMediumDateString()+“” +prev.getTitle()+“”; } 否则{ s+=”; s+=”; } 如果(下一步!=null){ s+=“

” +next.getDate().getMediumDateString()+“” +next.getTitle()+“”; } 否则{ s+=”; } s+=“\n”; 返回s; } 专用静态void generateChunks(Writer w,Vector notes){ Object[]n=notes.toArray(); for(int i=0;i0){ nprev=(注)n[i-1]; } 注nnext=null; 如果(i
如前所述,基本上您应该将应用程序逻辑从GUI代码中移出

单元测试通常不像编写工作代码然后添加测试那样工作

  • 什么是逻辑的可测试部分,什么不是
  • 你将如何把它们分开
  • 您将如何测试可测试部分
直接测试GUI代码通常不起作用(除了一些罕见且设计良好的UI框架),因为您的测试必须处理许多技术问题(如框架初始化、UI对象实例化、正确触发事件等)。因此,您应该为应用程序创建一个更抽象的层。从更大的角度来看,这将导致众所周知的模型-视图-控制器模式(自Smalltalk以来用户界面的事实上的标准设计模式),其中模型层独立于UI框架,因此它是可测试的

作为一种案例研究,让我们浏览一下上述概念:

首先,让我们检查哪些是可测试的,哪些不是,哪些阻止您编写测试:

setDialogTitle(Local.getString(“导出项目报告”))

这一行同时处理渲染和i18n,这不是一个好主意。此外,使用静态方法是一个顶级拦截器