2017-06-21 131 views
2

私はJUnittestingで新しく質問があります。誰も私たちがJunitテストの例でReflectionTestUtils.setField()を使う理由を教えてもらえますか?JunitテストでのReflectionTestUtils.setField()の使用

+0

達成しようとしていることと試したことを教えてください。 – Mritunjay

+0

[java doc](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html)は使い方をよく説明しています – Patrick

+0

私は見ましたBefore annotationでreflectiontestUtils.setField()を使用するjunitクラスの例ですが、なぜそれが使われているのか、何が必要なのか理解できません。基本を知りたいだけです。 @Mritunjay –

答えて

6

コメントに記載されているように、javaドキュメントは使い方をよく説明しています。しかし、私はあなたにも簡単な例を与えたいと思います。

プライベートフィールドまたは保護フィールドアクシデントを持つEntityクラスがあり、提供されたセッターメソッドがありません。あなたが見つからないためsetterメソッドのあなたのentityidを設定することはできませんあなたのテストクラスで

@Entity 
public class MyEntity { 

    @Id 
    private Long id; 

    public Long getId(Long id){ 
     this.id = id; 
    } 
} 

ReflectionTestUtils.setField(myEntity, "id", 1); 

パラメータが記述されています:

public static void setField(Object targetObject, 
          String name, 
          Object value) 
Set the field with the given name on the provided targetObject to the supplied value. 
This method delegates to setField(Object, String, Object, Class), supplying null for the type argument. 

Parameters: 
targetObject - the target object on which to set the field; never null 
name - the name of the field to set; never null 
value - the value to set 

しかし、試してみるとdocsをお読みください。あなたは、テストの目的のためにそれを行うことができますReflectionTestUtils.setFieldを使用して

+0

あなたの説明のために@Patrickに感謝します:) –

+0

ReflectionTestUtils.setField(accountServiceImpl、 "partyServiceImpl"、partyServiceImpl)のような値のペースでクラスオブジェクト(partyServiceImpl)を使用するともう1つの質問があります。毎回partyServiceImplオブジェクトをモックする必要がありますか? @パトリック –

+0

@rohitsharmaあなたのユースケースによって異なります。今はpartyServiceImplオブジェクトをaccountServiceImplオブジェクトに設定しています。テストのためにあなたのオブジェクトの値を保持する必要がある場合は、追加のモックが必要ありません – Patrick

関連する問題