我对单元测试有点新意,但我尝试模拟一个界面。它在设置中给出了一个nullpointer。任何人都可以帮我模仿这些物体吗?
以下是代码:
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;
}
答案 0 :(得分:2)
// tried this, but failes because mockito can't mock url.
所以,不要让mockito模仿一个URL。 Mockito不能模拟final
类。
@Mock
字段移除URL serviceEndPoint
; MockitoAnnotations.initMocks(this);
行serviceEndPoint = new URL("http://example.com");
。 example.com
域名是guaranteed not to be assigned(通过RFC),因此,如果您不小心嘲笑HttpURLConnection
,那么您永远不会最终与真实服务器交谈