[英]ByteBuddy agent test with gradle and JUnit5
當我嘗試測試使用 ByteBuddy 編寫的 Java 代理時,我遇到了一些奇怪的行為
代理攔截帶注釋的方法/類並分析它們,沒有什么復雜的
class ByteInstrumentationConfigurer implements BootstrapConfigurer {
@Override
void init(...) {
def instrumentation = ByteBuddyAgent.install()
new AgentBuilder.Default()
.type(isAnnotatedWith(TimeProfiling.class))
.transform((builder, typeDescription, classLoader, module) ->
builder.method(not(isAnnotatedWith(Generated))) //ignore groovy generated methods (getMetaClass, etc.)
.intercept(MethodDelegation.to(TimeProfilingInterceptor.class)))
.with(stdoutToLoggerWriter.withTransformationsOnly())
.installOn(instrumentation)
我有一些單元測試,我驗證攔截器方法被調用
class TimeProfilingInterceptorTest {
static MockedStatic<TimeProfilingInterceptor> timeProfilingInterceptorMockedStatic
static {
//agent installation happens here
new ByteInstrumentationConfigurer().init([:], [:])
timeProfilingInterceptorMockedStatic = mockStatic(TimeProfilingInterceptor, CALLS_REAL_METHODS)
}
@Test
void profilingEnabledClassLevelTest() {
//some mocking for my classes here
testCallingComponent.callClassLevelComponentMethod()
timeProfilingInterceptorMockedStatic.verify(()->
TimeProfilingInterceptor.measureAndLogExecutionTime(any(),any(),any()),times(2))
}
現在,當我使用 IDEA 開始這個測試時,我看到,我的 2 個類被轉換了
[字節好友] 轉換 com.kmslh.manager.profiling.components.MethodLevelTimeProfilingComponent [sun.misc.Launcher$AppClassLoader@18b4aac2, null, Thread[main,5,main],loaded=false]
[字節好友] 轉換 com.kmslh.manager.profiling.components.ClassLevelTimeProfilingComponent [sun.misc.Launcher$AppClassLoader@18b4aac2, null, Thread[main,5,main],loaded=false]
但是如果我使用gradle
test\\build 任務運行這個測試 - 沒有類轉換。 如果我輸出完整信息 - 我看到在這種情況下類加載器是org.codehaus.groovy.runtime.callsite.CallSiteClassLoader
。
[字節好友] 發現 com.kmslh.manager.profiling.components.ClassLevelTimeProfilingComponent$exposedMethod [org.codehaus.groovy.runtime.callsite.CallSiteClassLoader@3b1a332, null, Thread[Test worker,5,main],loaded=false] [字節好友] IGNORE com.kmslh.manager.profiling.components.ClassLevelTimeProfilingComponent$exposedMethod [org.codehaus.groovy.runtime.callsite.CallSiteClassLoader@3b1a332, null, Thread[Test worker,5,main],loaded=false] [字節Buddy] COMPLETE com.kmslh.manager.profiling.components.ClassLevelTimeProfilingComponent$exposedMethod [org.codehaus.groovy.runtime.callsite.CallSiteClassLoader@3b1a332, null, Thread[Test worker,5,main],loaded=false]
不確定這是否是一個問題,但我沒有想法。 我也嘗試將測試重寫為 Java - 沒有結果。
有什么建議可以嘗試嗎?
更新 1
從我所看到的 - 當測試從 gradle 開始時 - 沒有創建auxiliary
類
從您的日志中,Gradle 測試運行的類加載器與您的示例中運行的類加載器不同。 因此,我假設您的匹配器對正在使用的類加載器很敏感。 此外,請確保您的忽略匹配器不會在並行測試中排除類加載器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.