序文
我々は常に、コンストラクタにパラメータを渡すために使用される、エンコードされ、その後、powermockは、シミュレーションパラメータがそれを構築する方法で、これは難しいことではありません。
シミュレーションのシナリオ
のは、このようなシナリオをシミュレートしてみましょう、ブール型の中に入ってくるDAO(ロードされている場合)と列挙クラス(これは、データベースを使用)、構造ダオクラス、調製方法における学生の挿入
コードのDAO一部
コードの特定の例としては以下の通りであります:
パッケージcom.rongrong.powermock.mockconstructor。 / ** * @author rongrong * @version 1.0 * @date 2019年11月28日午前23時12 * / パブリック クラスStudentConstructorDao { パブリック 列挙でdatabaseType { MYSQL、 ORACLE、 } / ** * * @Param CsLoadすなわちリンクデータベースをロードするかどうか * @Param でdatabaseTypeデータベースタイプ * / パブリックStudentConstructorDao(ブールCsLoad、databaseTypeここでdatabaseType){ スロー 新しい新規にUnsupportedOperationException()。 } 公共 のボイドinsertStudent(StudentConstructor studentConstructor){ スロー 新)(UnsupportedOperationExceptionが。 } }
コードのサービスパーツ
ダオは、関数で使用される次のように特定のコードを呼び出します。
パッケージcom.rongrong.powermock.mockconstructor。 / ** * @author rongrong * @version 1.0 * @date 2019年11月28日午後11時18分 * / パブリック クラスStudentConstructorService { 公共 のボイドcreateStudnet(StudentConstructor studentConstructor){ StudentConstructorDao studentConstructorDaoは = 新しい StudentConstructorDao(偽、StudentConstructorDao.DataBaseType.MYSQLを)。 studentConstructorDao.insertStudent(studentConstructor)。 } }
書き込みテストケース
Powermockコンストラクタをシミュレートするために使用され、以下のようにテストサービスは、特定のコードがあります。
パッケージcom.rongrong.powermock.mockconstructor。 輸入org.junit.Test; 輸入org.junit.runner.RunWith; 輸入org.mockito.Mockito; 輸入org.powermock.api.mockito.PowerMockito; 輸入org.powermock.core.classloader.annotations.PrepareForTest; 輸入org.powermock.modules.junit4.PowerMockRunner; 輸入 静的com.rongrong.powermock.mockconstructor.StudentConstructorDao.DataBaseType.MYSQL。 / ** * @author rongrong * @version 1.0 * @date 2019年11月28日午後11時54分 * / @RunWith(PowerMockRunner。クラス) @PrepareForTest(StudentConstructorService。クラス) パブリック クラスTestStudentConstructorService { @テスト 公共 のボイドtestStudentConstructorService(){ StudentConstructorDao StudentConstructorDao = PowerMockito.mock(。StudentConstructorDao クラス); 試み{ // ここで必要のコメントの下でパラメータダオ、とき、彼はそのようなパラメータが初期化さえも偽のパラメータ、とターゲットを構築する必要が PowerMockito。 whenNew(。studentConstructorDao クラス).withArguments(falseに、MYSQLベース).thenReturn(studentConstructorDao)。 StudentConstructor studentConstructor = 新しいStudentConstructor(); StudentConstructorService studentConstructorService = 新しいStudentConstructorService(); studentConstructorService.createStudnet(studentConstructor)。 Mockito.verify(studentConstructorDao).insertStudent(studentConstructor)。 } キャッチ(例外e){ e.printStackTrace(); } } }
概要
- 最初のオブジェクトのインスタンスをモックStudentConstructorDao
- 使用whenNew文法は、上院で通過しなければならず、サービスパラメータの場所の引数に注意を払う必要があります、またはそれはStudentConstructorDao意志でサービスの新しいインスタンスを作成していきます
- そして、検証メソッドを呼び出します
注:Studentクラスは、ここでは省略する前に、コンストラクタのパラメータは記事を参照して、学生のクラスコードに、withAnyArguments()缶を使用して、決定することはできません