如何在Java中编写测试用例

如何在Java中编写测试用例

本文介绍了如何在Java中编写测试用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我创建了一个类ABC.java,并且有一个构造函数ABC()如下:

 公共类ABC {私有静态字符串主机;私有静态字符串端口;------公开ABC(){尝试 {File file = new File("Element.xml");DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();文档doc = db.parse(file); 

我正在传递Element.xml作为输入,我想测试此类,所以我创建了ABCTest类,请告诉我如何为上述代码编写构造函数ABC()的测试用例以及如何编写assert()

解决方案

尽管Selenium本身就是一个测试工具,但对我来说听起来好像您想测试该类本身.就像用jUNit进行测试一样.

使用您刚才提供的代码片段,没有什么要测试的,因为您还没有更改对象的状态.实例变量尚未初始化(尚未).构造函数可以执行某些操作,但不会产生结果.

您可以编写一个非常小的测试用例,以检查初始化期间是否没有引发异常.尽管这可能很困难,但是因为您在构造函数中捕获了异常.

并且您可以考虑在测试过程中将 System.out 重定向到字符串,并检查代码是否将预期的输出打印到控制台.

hi I created one class ABC.java, and there is one constructor ABC() as follows:

 public class ABC {

        private static String host;
        private static String port;
        ------

       public ABC(){
            try {

                  File file = new File("Element.xml");
                  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                  DocumentBuilder db = dbf.newDocumentBuilder();
                  Document doc = db.parse(file);

I am passing Element.xml as a input,I want to test this class,so I created ABCTest class,please tell me how to write test case for constructor ABC() and how to write assert(),for above code

解决方案

Although Selenium is a test tool itself, it sounds to me as if you want to test this class itself. Like implementing a test with jUNit.

With the snippet you just provided, there's not much to test, because you don't change the objects state (yet). The instance variables are not initialized (yet). The constructor does something but does not produce a result.

You could write a pretty small test case to check if there's not Exception being thrown during initialization. Although this may be difficult, because you catch exceptions in the constructor.

And you may consider redirecting System.out to a string during the test and check if the code prints the expected output to the console.

这篇关于如何在Java中编写测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:16