【问题标题】:Spring Data Rest testingSpring Data Rest 测试
【发布时间】:2019-05-05 20:19:45
【问题描述】:

我正在使用 Spring Data Rest 开发应用程序。如您所知,在创建简单的存储库接口后,rest-endpoints 由库创建。

我是否需要通过集成测试来测试这些端点?如果是,请提供任何示例

【问题讨论】:

  • 是的,我认为您绝对应该编写测试。你可以找到例子here
  • 是的,你可以用 MockMVC 测试它们

标签: spring spring-data-rest


【解决方案1】:

这里是代码 sn-p。阅读完整教程here

@Entity
@Table(name = "person")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Size(min = 3, max = 20)
    private String name;

    // standard getters and setters, constructors
}

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
    public Employee findByName(String name);
}


@RunWith(SpringRunner.class)
@SpringBootTest(
  SpringBootTest.WebEnvironment.MOCK,
  classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(
  locations = "classpath:application-integrationtest.properties")
public class EmployeeRestControllerIntegrationTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private EmployeeRepository repository;

    @Test
public void givenEmployees_whenGetEmployees_thenStatus200()
  throws Exception {

    createTestEmployee("bob");

    mvc.perform(get("/api/employees")
      .contentType(MediaType.APPLICATION_JSON))
      .andExpect(status().isOk())
      .andExpect(content()
      .contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
      .andExpect(jsonPath("$[0].name", is("bob")));
}
}

【讨论】:

  • 难道没有一种自动生成测试的方法来验证所有端点,就像@RepositoryRestResource 生成所有端点一样?
【解决方案2】:

除了您可以使用 Spring 进行常规测试(使用 MockMvc、RestAssured、RestTemplate 等)之外,Traverson 是专门用于测试 Spring HATEOAS 的出色 API。您可以使用它来测试您返回给客户的链接的有效性,请参阅example

【讨论】:

    猜你喜欢
    • 2016-04-17
    • 2018-11-19
    • 1970-01-01
    • 2017-01-19
    • 2020-04-04
    • 2016-10-26
    • 1970-01-01
    • 2017-04-27
    • 2014-10-26
    相关资源
    最近更新 更多