使用Junit进行Sping Boot测试

时间:2018-10-14 16:17:24

标签: spring spring-boot junit

使用Spring Boot 2.0.3.RELEASE

测试的目标是让服务在同一应用中调用控制器。

这是我正在尝试的简化设置

应用程序类

@SpringBootApplication
public class StartApp {
    public static void main(String[] args) {
        SpringApplication.run(StartApp.class, args);
    }
}

控制器类

@RestController
public class EmpCtrl {

    private static final Logger logger = LoggerFactory.getLogger(EmpCtrl.class);

    @Autowired
    private EmpDao empDao;

    @RequestMapping(value = "/emp01", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
    public List<Emp> findAllEmp01() {
        logger.trace("running my.demo.controller.findAllEmp01");
        List<Emp> emps = new ArrayList<>();
        Iterable<Emp> results = this.empDao.findAll();
        results.forEach(emp -> {emps.add(emp);});
        return emps;
    }
}

服务类别

@Service
public class GetEmpSrv {
    private static final Logger logger = LoggerFactory.getLogger(GetEmpSrv.class);

    public void getEmps01(){
        final String uri = "http://localhost:8080/emp01";
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(uri, String.class);
        logger.debug(result);
    }
}

和Junit类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartApp.class)
public class GetEmpSrvTest01 {

    @Test
    public void doCall() {
        GetEmpSrv getEmpSrv = new GetEmpSrv();
        getEmpSrv.getEmps01();
    }
}

此文件正在Eclipse Oxygen.3a(4.7.3a)内部运行

在控制台中,似乎Spring Boot正在运行..ic,h2 db和/ emp01的负载已映射,但是在Junit ic的失败跟踪中

I/O error on GET request for "http://localhost:8080/emp01": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect

这使我认为嵌入式Tomcat没有运行。当我正常启动Spring时,/ emp01会按预期返回JSON。

我的问题是:Junit可以进行这种测试吗?如果是这样,我需要怎么做才能使其正常工作?

1 个答案:

答案 0 :(得分:1)

在测试中,请自动连接TestRestTemplate。原因是您的弹簧测试将在另一个端口上运行,并且对http://localhost:8080的调用将失败。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = StartApp.class)
public class GetEmpSrvTest01 {

    @Autowired
    TestRestTemplate testRestTemplate;

    @Test
    public void doCall() {
        // without http://localhost:8080, testRestTemplate it will handle it for you
        testRestTemplate.getForObject("/emp01", String.class);
    }
}

您还可以在测试中获得对象列表:

List<Emp> emps = testRestTemplate.getForObject("/emp01", List.class);