Spring数据静止测试

jmp7cifd  于 2023-05-27  发布在  Spring
关注(0)|答案(3)|浏览(119)

我正在使用Spring Data Rest开发应用程序。如您所知,在创建简单的存储库接口之后,rest-endpoints由库创建。
我需要通过集成测试来测试这些端点吗?如果是,请举例说明

siotufzp

siotufzp1#

下面是代码片段。阅读完整教程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")));
}
}
2izufjch

2izufjch2#

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

rdlzhqv9

rdlzhqv93#

使用https://github.com/Cosium/hal-mock-mvc,您可以按以下方式测试它们:

@AutoConfigureHalMockMvc
   @SpringBootTest
   class MyTest {
     @Autowired
     private HalMockMvc halMockMvc;
   
     @Test
     void test() {
       halMockMvc
          .follow("current-user")
          .get()
          .andExpect(status().isOk())
          .andExpect(jsonPath("$.alias").value("jdoe"));
     }
   }

相关问题