2016-05-23 18 views
0

私はunittestingに少し新しいですが、私はインターフェイスを模擬しようとします。これは、セットアップでヌルポインタを与えます。誰も私がこれらのオブジェクトを嘲笑するのを助けることができる?ここでインターフェイスモックgevis 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

あなたは 'URL serviceEndPoint'から' @ Mock'を削除し、手でインスタンス化することを検討しましたか? –

+0

はい、それ以降は(このURLからの)エンドポイントへの接続を開きたいとします。私は実際に接続を開けたくないので、私はURLオブジェクトを嘲笑したい...私はこれを使うテストの1つで:when(serviceEndPoint.openConnection())。then return(connection); – JohannisK

+0

''接続 'は実際には開かれません - それはモックです。 –

答えて

2

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

、URLを模擬するmockitoを聞きません。モッキートは模擬できませんfinalクラス。

  • URL serviceEndPointフィールドから@Mockを削除します。
  • MockitoAnnotations.initMocks(this);行を復活させる
  • すぐに、serviceEndPoint = new URL("http://example.com");と書いてください。

example.comドメインは、(RFCによる)guaranteed not to be assignedあるので、あなたが誤ってHttpURLConnectionを模擬しなかった場合は、実サーバに話して終わることはありませんでした。

+0

ありがとう、これはもう少し私を得る。しかし、serviceEndPointが有効なURLインスタンスである場合、どうすればこのことを気にすることができますか?(serviceEndPoint.openConnection())。then return(connection); serviceEndPointがもうモックではないので、今は動作しません – JohannisK

+0

[PowerMockito](http://vaguehope.com/2012/02/powermock-puzzler/)を使用する必要があります。 –

+0

Hmmm ....実際にはしたくない... ClassToTestは公式に実際の接続を行い、リクエストを実行するクラスなので、このクラスを接続したいと思っていましたが、インターフェースをpublic URL getServiceEndpoint()をpublic HttpURLConnection getServiceConnection()に設定します。これは私が思うようにテストするのがより賢明になるでしょうか? – JohannisK

関連する問題