0

我是使用 Mockito 测试框架的新手。我需要对一种返回字符串内容的方法进行单元测试。同样的内容也将存储在一个 .js 文件中(即“8.js”)。如何验证从该方法返回的字符串内容是否符合我的预期。

请找到以下用于生成 .js 文件的代码:

public String generateJavaScriptContents(Project project)
   {

      try
      {
         // Creating projectId.js file
         FileUtils.mkdir(outputDir);
         fileOutputStream = new FileOutputStream(outputDir + project.getId() + ".js");
         streamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
         StringTemplateGroup templateGroup =
            new StringTemplateGroup("viTemplates", "/var/vi-xml/template/", DefaultTemplateLexer.class);
         stringTemplate = templateGroup.getInstanceOf("StandardJSTemplate");
         stringTemplate.setAttribute("projectIdVal", project.getId());
         stringTemplate.setAttribute("widthVal", project.getDimension().getWidth());
         stringTemplate.setAttribute("heightVal", project.getDimension().getHeight());
         stringTemplate.setAttribute("playerVersionVal", project.getPlayerType().getId());
         stringTemplate.setAttribute("finalTagPath", finalPathBuilder.toString());
         streamWriter.append(stringTemplate.toString());
         return stringTemplate.toString();
      }
      catch (Exception e)
      {
         logger.error("Exception occurred while generating Standard Tag Type Content", e);
         return "";
      }

   }

上述方法的输出写入 .js 文件,该文件的内容如下所示:

变量投影= 8;
var playerwidth = 300;
var playerheight = 250;
var player_version = 1;
......

我已经编写了testMethod()using mockito 来测试它,但是我能够使用 test 方法成功编写 .js 文件,但是如何验证它的内容?

谁能帮我解决这个问题?

4

2 回答 2

4

As @ŁukaszBachman mentions, you can read the contents from the js file. There are a couple of things to consider when using this approach:

  1. The test will be slow, as you will have to wait for the js content to be written to the disk, read the content back from the disk and assert the content.
  2. The test could theoretically be flaky because the entire js content may not be written to the disk by the time the code reads from the file. (On that note, you should probably consider calling flush() and close() on your OutputStreamWriter, if you aren't already.)

Another approach is to mock your OutputStreamWriter and inject it into the method. This would allow you to write test code similar to the following:

OutputStreamWriter mockStreamWriter = mock(OutputStreamWriter.class);
generateJavaScriptContents(mockStreamWriter, project);
verify(mockStreamWriter).append("var projectid = 8;\nvar playerwidth = 300;...");

http://mockito.googlecode.com/svn/branches/1.5/javadoc/org/mockito/Mockito.html#verify%28T%29

于 2012-06-11T04:16:44.070 回答
0

如果您将此*.js文件保存在文件系统上,则只需创建 util 方法,该方法将读取其内容,然后使用某种方式assertEquals将其与您的固定数据进行比较。

是将文件内容读入String.

于 2012-06-10T20:27:25.483 回答