java - 如何为下面的类编写junit测试用例

标签 java unit-testing junit

我正在使用 Mockito 学习 JUnit。我对如何开始以及如何为下面的类(class)编写单元测试有任何想法。如果有人能帮助我写它们,我会很高兴:

@Service
public class GetDataFromHistDataImpl implements GetDataFromHistData{    

  @Override
  public File downloadData(String formUrl) {
    String tk = null;
    String date= null;
    String datemonth= null;
    String platform= null;
    String timeframe= null;
    String fxpair= null;

    WebClient webClient=new WebClient();

    try 
    {
        HtmlPage page1=webClient.getPage(formUrl);
        webClient.getOptions().setJavaScriptEnabled(false); 
        HtmlForm form=page1.getFormByName("file_down");
        tk=form.getInputByName("tk").getAttribute("value");
        date=form.getInputByName("date").getAttribute("value");
        datemonth=form.getInputByName("datemonth").getAttribute("value");
        platform=form.getInputByName("platform").getAttribute("value");
        timeframe=form.getInputByName("timeframe").getAttribute("value");;
        fxpair=form.getInputByName("fxpair").getAttribute("value"); 
        System.out.println("fx"+fxpair);
        webClient.close();

    } 
    catch (IOException e1) {
        e1.printStackTrace();
    }

    Client client = ClientBuilder.newBuilder().build();

    WebTarget target = client.target("http://www.histdata.com/get.php");

    MultivaluedMap<String, String> map = new MultivaluedStringMap();
    map.add("tk", tk);
    map.add("date", date);
    map.add("datemonth", datemonth);
    map.add("platform", platform);
    map.add("timeframe", timeframe);
    map.add("fxpair", fxpair);

    InputStream responseStream = target.request().header("Referer", "http://www.histdata.com/")
            .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
            .header("Accept-Encoding", "tar, deflate")
            .post(Entity.form(map), InputStream.class);

        File file = new File("data.tar");

        OutputStream fos;
        try 
        {
            fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int len;

            while ((len = responseStream.read(buffer)) != -1)
            {

                fos.write(buffer, 0, len);
            }
            fos.close();
        }       
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();    
        }

        return file;
}

@Override
public File unZipData(File zipFile) {
    byte[] buffer = new byte[1024];
    final String OUTPUT_FOLDER = "/Users/venkateswara/Downloads/Sindhu/histdata";
    File returnFileName=null;
     try{

        File folder = new File(OUTPUT_FOLDER);
        if(!folder.exists()){
            folder.mkdir();
        }

        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();

        if(ze==null)
        {
            System.out.println("ZipFile is empty or corrupted");
            System.exit(0);
        }

        while(ze!=null){

           String fileName = ze.getName();
           File newFile = new File(OUTPUT_FOLDER + File.separator + fileName);
           if(FilenameUtils.getExtension(newFile.getName()).contains("csv"))
           {
               returnFileName=newFile.getAbsoluteFile();
           }

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);             

            int len;
            while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
            }

            fos.close();   
            ze = zis.getNextEntry();
        }   
        zis.closeEntry();
        zis.close();    
    }
     catch(IOException ex){
       ex.printStackTrace(); 
    }
  return returnFileName;    

}

private InsertHistDao insertHistDao;

@Autowired
public void setInsertHistIntoDb(InsertHistDao insertHistDao) {
    this.insertHistDao = insertHistDao;
}


@Override
public void getDataFromCsv(File unZipFile,String sym) {
    String[] csvLine=null;
    try 
    {
        CSVReader csvReader=new CSVReader(new FileReader(unZipFile));
        while((csvLine=csvReader.readNext())!=null)
        {
            System.out.println("data :"+Arrays.toString(csvLine));
            insertHistDao.insertHistIntoDb(csvLine,sym);
            rowsInserted++;
            System.out.println("Rows inserted:"+rowsInserted);
        }
        csvReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
   }
  }

这是我想要进行单元测试的类。

最佳答案

一般来说,你想听这些videos 。严重地;如果您想做单元测试,那么您应该退后一步并理解它的真正含义

就您而言,您的代码无法轻松测试。 开始:您的方法确实使用new创建了它正在使用的 webClient 对象。这意味着:您的测试代码无法控制该对象。没有控制,测试是不可能的!

相反,您可以使用依赖注入(inject)。这意味着:您创建一种方法,以便您的测试代码可以为您的测试代码提供模拟 webClient 对象。然后你可以简单地描述:我希望这个调用发生在我的模拟上;然后,应该返回该值。

但是,当然,这只是方法中的第一个对象。您的另一个问题是您在该方法中做了太多事情。相反,你必须分解成许多更小的东西。然后,您创建更多具有不同功能的类/对象。然后你自己测试它们。

所以,长话短说:

  1. 您确实必须退后一步才能理解从单元测试中获益的代码......必须以非常不同的方式编写!
  2. 为了充分利用单元测试;你不仅要学习“单元测试实践”和框架,还要学习“如何创建干净的代码”和SOLID OO 设计。

关于java - 如何为下面的类编写junit测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38913449/

相关文章:

java - 连接到 CouchDB 时强制设置连接超时

java - 为什么我的代码会打印两次玩家姓名?

java - 无法从 Spring 获取带有附加凭据的 HttpServletRequest

c# - 如何在 CRM 2011 开发中编写单元测试

java - 在 Java 中使用 Redis 异步命令对 void 方法进行单元测试

java - 如何捕获事件调度线程 (EDT) 异常?

asp.net-mvc - ASP.Net Web API Controller 单元测试 POST

ruby-on-rails - 在编写单元/功能测试时考虑缓存

java - WebDriver 未在 Cucumber 测试中实例化

testing - 我如何断言接受 JUnit 中的多个可能值之一