2017-10-30 8 views
0
public class MyXML { 
    private MessageParser messageParser; 
    private String valueA; 
    private String valueB; 
    private String valueC; 

    public MyXML (MessageParser messageParser) { 
     this.messageParser=messageParser; 
    } 

    public void build() { 
     try { 
      setValueA(); 
      setValueB(); 
      setValueC(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private void setValueA() { 
     valueA = messageParser.getArrtibuteUsingXPath("SomeXPath1..."); 
    } 

    private void setValueB() { 
     valueB = messageParser.getArrtibuteUsingXPath("SomeXPath2..."); 
    } 

    private void setValueC() { 
     valueC = messageParser.getArrtibuteUsingXPath("SomeXPath..."); 
    } 

    public String getValueA() { 
     return valueA; 
    } 

    public String getValueB() { 
     return valueB; 
    } 

    public String getValueC() { 
     return valueC; 
    } 
} 

ビルダーメソッドをテストするには、Mockitoを使用する必要があります。私はビルダーメソッドのテストを書く方法について、誰かに私にいくつかのコード例を教えてもらえますか?Java Mockitoを使用してビルダーメソッドをテストする方法1.10.19

クラスのデザインを変更したり、テストしやすくする方法を提案したい場合は、教えてください。 (ビルドをテストする

+0

まず、 'getValueA()'、 'getValueB()'、...はロジックを含まず、単純な文字列を返すだけです。 – john

+0

コンストラクタを使って ' messageParser'は優れた設計であり、テストを容易にします。 'messageParser'をモックし、' when ... thenReturn ... 'を介してモック値を返すように設定します。次に、それらの値がパブリックメソッドで返されたことを単にアサートします。例を検索してください。 –

+0

MessageParserを擬似して、メッセージパーサーをMyXMLオブジェクトに挿入すると、java.lang.AssertionErrorが返されます。期待値:が、236523 –

答えて

0

)あなたが試すことができます:

@RunWith(MockitoJUnitRunner.class) 
public class YourTest { 
    @Mock 
    private private MessageParser messageParserMock; 

    // this one you need to test 
    private MyXML myXML; 

    @Test 
    public void test() { 
     myXML = new MyXML(messageParserMock); 

     // I believe something like this should work 
     Mockito.doAnswer(/* check mockito Answer to figure out how */) 
      .when(messageParserMock).getArrtibuteUsingXPath(anyString()); 
     // you should do this for all your 3 getArrtibuteUsingXPath because setValueA(), setValueB(), setValueC() are called that one and then call build and verify results 

     myXML.build(); // for instance 
     assertEquals("something you return as Answer", myXML.getValueA()); 
    } 
} 

をリソースhttps://static.javadoc.io/org.mockito/mockito-core/2.8.9/org/mockito/Mockito.html#stubbing_with_exceptionsが役に立つかもしれない - それは、ボイドのメソッドが呼び出すスタブする方法について説明します。

関連する問題