2

コンパイル時にアスペクトを織り込むために、 aspectj maven プラグインを使用しています。@Adviceアプリケーションを実行すると、最初にアドバイスが呼び出される直前に、注釈付きのクラスがインスタンス化されます。例えば:

@Aspect
public class MyAdviceClass {

    public MyAdviceClass() {
        System.out.println("creating MyAdviceClass");
    }

    @Around("execution(* *(..)) && @annotation(timed)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, Timed timed) throws Throwable {
        System.out.println("timed annotation called");
        return pjp.proceed();
    }
}

アノテーションを使用するメソッドがある場合、@Timedそのメソッドが初めて呼び出されたときに「作成中の MyAdviceClass」が出力され、「時間指定されたアノテーションが呼び出されました」が毎回出力されます。

いくつかのコンポーネントをモックしてアドバイスの機能を単体テストしたいと思いますが、Spring Beans ではなく AspectJ によってインスタンス化されるMyAdviceClassため、これを行うことはできません。MyAdviceClass

このような単体テストのベストプラクティス方法は何ですか?

4

1 に答える 1

0

私は解決策を見つけたので、これに遭遇した他の人のために投稿したいと思います。トリックはfactory-method="aspectOf"、Spring Bean 定義で使用することです。上記の例を使用して、この行をapplicationContext.xml

<bean class="com.my.package.MyAdviceClass" factory-method="aspectOf"/>

私の単体テストは次のようになります。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext.xml")
public class MyAdviceClassTest {
    @Autowired private MyAdviceClass advice;
    @Mock private MyExternalResource resource;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
        advice.setResource(resource);
    }

    @Test
    public void featureTest() {
        // Perform testing
    }
}

詳細については、こちらをご覧ください

于 2014-02-13T19:22:49.290 に答える