gpt4 book ai didi

java - 测试 REST Web 服务时出现空指针异常

转载 作者:行者123 更新时间:2023-12-01 11:11:25 24 4
gpt4 key购买 nike

尝试测试 Web 服务时出现 NullPointerException

我的代码:

@Path("/")
public class SubscriptionService {

@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/status/{subsId}")
public Response getSubscriptionStatus(@PathParam("subsId") int subsId) {
return Response.status(200).entity("subscription status for id: " + subsId).build();
}
}

测试类:

public class TestService {

private SubscriptionService service;

@Test
public void testGetSubscriptionStatus() {
final Response response = service.getSubscriptionStatus(5);

Assert.assertEquals(200, response.getStatus());
Assert.assertEquals("subscription status for id: 5", response.getEntity());
}
}

错误出现在此处:final Response response = service.getSubscriptionStatus(5);

有人知道我为什么会收到此错误吗?

最佳答案

您永远不会初始化服务。所以你会得到一个 NPE。

更改:

private SubscriptionService service;

致:

private SubscriptionService service = new SubscriptionService();

关于java - 测试 REST Web 服务时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32312167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com