テストツール(junit,mockito)

2065 ワード

ビジネステストでは、springコンテナをロードしてビジネステストを行う必要がある場合があります.@Autowiredロードサービスを通じて、@Testがテスト例を実行することで、多くの公開方法のテストを実現することができます.
しかしSpringコンテナのロードは長い.Springコンテナ全体をロードしたくない場合は、mock方式でいくつかの依存オブジェクトをロードできます.
さらにmock方式を用いてクラスのプライベートメソッドをテストすることができる.また、オブジェクト内の任意のドメインの値(プライベートドメインを含む)を動的に変更することもできます.
アクセス方法は次のとおりです.
1.導入依存


    org.springframework
    spring-test
    4.1.1.RELEASE
    test


    junit
    junit
    4.9
    test


    org.mockito
    mockito-core
    1.10.19
    test

2.テストクラスにおいてmockがテスト対象のクラス実装を出す
@InjectMocks
private someServiceImpl someService;

3.mockから出たクラスのプライベートメソッドを呼び出し、クラス内のプライベートドメインを設定します.
@Injectable 
CService cService;

@Test
public void someTest() {
    //  
    ReflectionTestUtils.setField(someService, "variableName", variable);
    //  ( ) 
    MethodResult methodResult = ReflectionTestUtils.invokeMethod(someService, "methodName", arg1, arg2);

    //  、 
    new Expectations() {{
        AService.aMethod(anyInt, any);
        result = false;
        Deencapsulation.invoke(BServiceImpl.class, "privateMethod", anyInt, anyInt, anyInt, any);
        result = Lists.newArrayList(new BServiceTO(1));
    }}
    //  , 
    cService = new MockUp(CService.class) {
        @Mock
        Model addModel(Integer userId, Long time) {
            Model m = new Model();
            m.setUserId(userId);
            m.setModifyTime(time);
            return m;
        }
    }.getMockInstance();
    Deencapsulation.setField(target, "cService", cService);
}

クラスのプライベートメソッドをロードすると、外部から直接呼び出すことはできません.オブジェクトのプライベート変数をReflectionTestUtilsで変更し、オブジェクトのプライベートメソッドを呼び出すことができます.(借用反射)