Junit不会调用REST Web服务

时间:2012-08-12 06:49:14

标签: rest java-ee junit resteasy

我想测试一个调用RESTEasy Web服务的类。似乎Junit没有调用web服务。我在服务器端检查过,请求没有到达。

public class EmpService {

  public List<Employee> getEmployees() {
      ClientRequest request = new ClientRequest("http://localhost:8080/rest/employees");
      request.accept(MediaType.APPLICATION_JSON);
      ClientResponse<Employees> response = null;

      try {
        response = request.get(Employees.class);
      } catch (Exception e) {
        e.printStackTrace();
      }

      Employees received = response.getEntity();
      if (received.getEmployees() == null){
        System.out.println("Employees is null");
      }
      return received.getEmployees();
    }
  }

我的目的不是测试REST服务,而是测试类EmpService。所以我编写了以下JUnit测试用例。

public class EmpServiceTest {

  @Test
  public void testGetEmployees() throws Exception {
    EmpService service = new EmpService();        
    List<Employees> employees = service.getEmployees();
    Assert.assertNotNull("Employees is null", employees);
  }

  @Test
  public void testREST() {
      ClientRequest request = new ClientRequest("http://localhost:8080/rest/employees");
      request.accept(MediaType.APPLICATION_JSON);
      ClientResponse<Employees> response = null;

      try {
        response = request.get(Employees.class);
      } catch (Exception e) {
        e.printStackTrace();
      }

      Employees received = response.getEntity();
      Assert.assertNotNull("Employees is null", received.getEmployees());
    }
}

我在浏览器中测试了REST服务,它运行正常。但是Junit测试用例无法调用它并且没有报告错误。 我试图直接在JUnit中测试REST服务。

1 个答案:

答案 0 :(得分:0)

我发现问题出在内容类型上。 JUnit端没有json映射器类。使用了jackson json库,它运行良好。