0
這是我想測試的代碼。該代碼運行良好,因爲我有資源(它應該是)的dependency.xml。它正確執行。Mockito Java測試總是通過 - 我做錯了什麼?
@Component
public class ProjectBuilderBean {
public List<String> getDependencyList() {
List<String> listDeps = new ArrayList<String>();
try {
ClassLoader classLoader = getClass().getClassLoader();
File xmlFile = new File(classLoader.getResource("dependency.xml").getFile());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
NodeList nList = doc.getElementsByTagName("dependency");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String dependency = eElement.getElementsByTagName("artifactId").item(0).getTextContent();
listDeps.add(dependency);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return listDeps;
}
}
這是我寫的測試,由於某種原因它總是通過。我不明白爲什麼以及如何通過,但我知道它不應該這樣做。我沒有向列表添加任何內容,並且它仍然通過,即使當我添加它時也是如此。這裏是測試:
@WebAppConfiguration
public class ProjectBuilderBeanTest {
@Mock
private ProjectBuilderController projectBuilderBeanMock;
//Decleration of the Class Instance
@Mock
ProjectBuilderBean projectBuilderBean;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
//Initialise the mocking of the class
projectBuilderBean = Mockito.mock(ProjectBuilderBean.class);
}
@Test
public void getDependencyListTest() throws Exception {
ArrayList<String> result = new ArrayList<String>();
result.add("a");
result.add("b");
when(projectBuilderBean.getDependencyList()).thenReturn(result);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
projectBuilderBean = null;
}
}
只是試圖測試通過dependency.xml文件生成的列表的一致性。
這裏是depenedency.xml的截圖:http://screenshot.net/3qoe4s0
我不確定你的測試方法是否真的測試任何東西。它只是告訴模擬對象它將不得不返回的方法調用。 – Berger
另外,你的代碼不好。只要它將被打包成一個jar文件,它就不會工作了。 ClassLoader加載的資源不是文件。傳遞一個uri或一個InputStream來解析(),而不是一個文件。 –
您能否指出我的方向,至少可以讓我開始吧@Berger? –