[英]Using Mockito, how do I verify a method was a called with a certain argument?
[英]How do i verify string content using Mockito in Java
我是使用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文件,該文件的內容如下所示:
var projectid = 8;
var playerwidth = 300;
var playerheight = 250;
var player_version = 1;
.....
我已經使用testMethod()
編寫了testMethod()
來對此進行測試,但是我能夠使用該測試方法成功編寫.js文件,但是如何驗證其內容?
誰能幫我解決這個問題?
正如@ŁukaszBachman提到的,您可以從js文件中讀取內容。 使用此方法時,需要考慮以下幾點:
另一種方法是模擬您的OutputStreamWriter
並將其注入該方法。 這將使您可以編寫類似於以下內容的測試代碼:
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
如果將這個*.js
文件持久化在文件系統上,則只需創建util方法即可讀取其內容,然后使用某種assertEquals
將其與固定數據進行比較。
這是將文件內容讀入String
代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.