接口Mock gevis nullpointer异常

时间:2016-05-23 12:46:49

标签: java junit

我对单元测试有点新意,但我尝试模拟一个界面。它在设置中给出了一个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;
            }

1 个答案:

答案 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,那么您永远不会最终与真实服务器交谈