在 Java 中放心测试特定方法

Test a particular method with rest-assured in Java

我想在一个名为 AdRestService 的 class 中测试一个特定的方法,它有一些 @GET、@POST 等。我想从另一个名为 class 的测试中测试它AdRest 服务测试。我想知道如何从 AdRestServiceTest 调用 AdRestService 中的方法以及如何测试 return 是否正常。

public class AdRestService {

    @GET
    @Path("{id}")
    @Produces("application/json")
    public Ad get(@PathParam("id") Long adId) {
        return adService.get(adId); // This points to the DB
    }

}

现在放心测试:

public class AdRestServiceTest {

    @InjectMocks
    private AdRestService adRestService;

    @Test
    public void getAdTest() {
        given().
        when().
            get("website.com/ad").
        then().
            assertThat().
            statusCode(200).
        and().
            contentType(ContentType.JSON).
        and().
            // ???
                // How can I call the method get(@PathParam("id") Long adId) from AdRestService and test if the return is correct ?
    }




}

我猜你混淆了 integrationunit tests。 Rest-assured 用于集成测试,因此它们测试您的应用程序服务器是否正确响应您定义的请求。您实际上会定义一个带有预期答案的 .json 文件,并将其与实际响应相匹配,以检查您的应用程序服务器的序列化是否正常工作。

参见 this 示例。

如果你想测试你AdRestService中的方法,你会写一个普通的单元测试,没有必要使用rest-assured。