gpt4 book ai didi

java - 接口(interface)模拟gevis空指针异常

转载 作者:行者123 更新时间:2023-12-02 03:36:26 25 4
gpt4 key购买 nike

我对单元测试有点陌生,但我尝试模拟接口(interface)。它在设置中给出了一个空指针。谁能帮我模拟这些对象?

这是代码:

public class ClassToTest
{

@Mock private RequestContainer request;
@Mock URL serviceEndPoint;
@Mock HttpURLConnection connection;

@Before
public void setup() {
try
{
//MockitoAnnotations.initMocks(this); // tried this, but failes because mockito can't mock url.
when(request.getServiceEndpoint()).thenReturn(serviceEndPoint); //nullpointer here
}
catch(MalformedURLException e)
{
// setup failed!
assertTrue("setup failed, unable to create mock for service endpoint....", false);
}
}
}
<小时/>
 public interface RequestContainer
{
public String getJson() throws JsonProcessingException;
public String getRequestMethod();
public String getWebsiteKey();
public String getSecretKey();
public URL getServiceEndpoint() throws MalformedURLException;
}

最佳答案

// tried this, but failes because mockito can't mock url.

所以,不要要求mockito 模拟URL。 Mockito 无法模拟 final 类。

  • URL serviceEndPoint 字段中删除 @Mock
  • 恢复 MockitoAnnotations.initMocks(this);
  • 紧接着,写入 serviceEndPoint = new URL("http://example.com");

example.com 域是 guaranteed not to be assigned (通过 RFC),因此,如果您不小心没有模拟 HttpURLConnection,那么您永远不会与真正的服务器通信。

关于java - 接口(interface)模拟gevis空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37391415/

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