簡體   English   中英

Mockito Java測試始終通過-我做錯了什么?

[英]Mockito Java Test Always Passes - What am I doing wrong?

這是我要測試的代碼。 該代碼運行良好,因為我在資源中(應位於的位置)具有dependency.xml。 它正確執行。

@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

只是為了回應評論者,但是您的“測試”始終通過的原因是因為您沒有測試任何東西。 您正在“執行”您的代碼。 您沒有斷言任何副作用,也沒有驗證任何模擬調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM