首页 > 解决方案 > 在 Spring Boot 中对 exportcsv 进行 Junit 测试

问题描述

嗨,我是 spring 的新手,并创建了一个带有两个控制器的 Export csv 应用程序,这些控制器可以提供所有数据以及选择性列数据,并希望为其编写 junit,但我很难像我一样做同样的事情不知道我应该怎么做一些帮助真的很棒主课:

package com.example;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.example.model.Example;

import com.example.repository.ExampleRepository;

import net.bytebuddy.implementation.bind.annotation.Super;

@SpringBootApplication
public class ExampleApplication implements CommandLineRunner   {
    
    @Autowired 
    ExampleRepository exampleRepository;
    
    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
    @Override
    public void run(String... args) throws Exception {
        

        
        
        List<Example> example= new ArrayList<>();

        // create dummy 
        example.add(new Example(1,"abc","sachin","abc","abc"));
        example.add(new Example(2,"abc","rahul","abc","abc"));
        example.add(new Example(3,"abc","rahul","abc","abc"));
        
        exampleRepository.saveAll(example);

    }
    
    
        
}

实体层:

package com.example.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="example")
public class Example{
    @Column(name="city")
    private String city;
    @Column(name="name")
    private String name;
    @Column(name="amount")
    private String amount;
    @Column(name="country")
    private String country;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private long id;
    //getter and setters
    }

存储层如下:

package com.example.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.example.model.Example;


@Repository("exampleRepository")
public interface ExampleRepository extends JpaRepository<Example,Long> {
    
    List<Report> findByName(String name);

}

服务层如下

package com.example.services;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.example.model.Example;
import com.example.repository.ExampleRepository;
@Transactional
@Service
public class ExampleService {
    @Autowired
    ExampleRepository exampleRepository;
    

    public List<Example> fetchAll() {
        return exampleRepository.findAll();
       

    }
    
    public List<Example> findByName(String name){
        return exampleRepository.findByName(name);
        
    }


    
}

我有 2 个控制器,一个用于获取所有详细信息,一个用于获取选择性列,这里我们根据与名称匹配的记录生成 csv 文件

控制器 1:

package com.example.controllers;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;

@RestController
@RequestMapping("/demo")
public class Controller1 {
    @Autowired
    ExampleService exampleService;
    @GetMapping("/result")
    public void exportCSV(@RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {

        // set file name and content type
        String filename = "names.csv";
        response.setContentType("text/csv");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, 
                   "attachment; filename=\"" + filename + "\"");

        // Configure the CSV writer builder
        StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);

       
        // create a csv writer
        StatefulBeanToCsv<Example> writer = builder.build();

        // write all employees to csv file
        writer.write(examplesService.findByName(name));

    }  

}

控制器 2:

package com.reports.controllers;

import java.util.Arrays;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;

@RestController
@RequestMapping("/example")
public class Controller2 {

    @Autowired
    ExampleService exampleService;

    @GetMapping("/output")
    public void exportCSV(@RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {

        // set file name and content type
        String filename = "details.csv";
        response.setContentType("text/csv");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, 
                   "attachment; filename=\"" + filename + "\"");

        // Configure the CSV writer builder
        StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);

     // Ignore any field except the `id` and `amount` ones
        Arrays.stream(Example.class.getDeclaredFields())
                .filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())
                        ))
                .forEach(field -> builder.withIgnoreField(Report.class, field));
      

        // create a csv writer
        StatefulBeanToCsv<Example> writer = builder.build();

        // write all employees to csv file
        writer.write(exampleService.findByname(name));

    }
}

标签: javaspring-bootunit-testingjunitjunit5

解决方案


试试这种方法:

  • 在您的路径中生成一个文件,/src/test/resources然后测试它是否包含您期望的生成数据
  • 使用将它与文件系统模拟结合起来

你会 :

  • 测试你的ResController
  • 嘲笑你的Service班级

Contructor Injection用于你的依赖


推荐阅读