gpt4 book ai didi

java - ThreadWeaver 总是抛出 IllegalArgumentException

转载 作者:行者123 更新时间:2023-12-02 06:15:35 24 4
gpt4 key购买 nike

我正在尝试使用 Google ThreadWeaver 为并发代码编写单元测试。无论我做什么,我都会得到一个 IllegalArgumentException。我仍在使用一个示例,但即使这样也不起作用。这是我尝试过的:

public class ExampleTest {
public static class ExampleMain implements MainRunnable<Example> {
private Example example;
@Override
public Class<Example> getClassUnderTest() {
return Example.class;
}
@Override
public String getMethodName() {
return null;
}
@Override
public Method getMethod() throws NoSuchMethodException {
return null;
}
@Override
public void initialize() throws Exception {
example = new Example();
}
@Override
public Example getMainObject() {
return example;
}
@Override
public void terminate() throws Exception {
}

@Override
public void run() throws Exception {
example.test("second");
}
}

public static class ExampleSecondary implements SecondaryRunnable<Example, ExampleMain> {

private ExampleMain exampleMain;

@Override
public void initialize(ExampleMain main) throws Exception {
exampleMain = main;
}

@Override
public void terminate() throws Exception {
}

@Override
public boolean canBlock() {
return false;
}

@Override
public void run() throws Exception {
exampleMain.getMainObject().test("main");
}
}

public static class Example {
private List<String> list = new ArrayList<String>();
public String test(String s) {
System.out.println("1" + s);
list.add(s);
System.out.println("2" + s);
return list.get(0);
}
}

@Test
public void testThreadWeaver() throws Exception {
ClassInstrumentation instrumentation = Instrumentation.getClassInstrumentation(Example.class);
Method tested = Example.class.getDeclaredMethod("test", String.class);
Method breakpoint = List.class.getDeclaredMethod("add", Object.class);
CodePosition codePosition = instrumentation.afterCall(tested, breakpoint);
InterleavedRunner.interleave(new ExampleMain(), new ExampleSecondary(), Arrays.asList(codePosition)).throwExceptionsIfAny();
}

}

堆栈跟踪显示:

java.lang.IllegalArgumentException: Class Example is not instrumented at com.google.testing.threadtester.CallLoggerFactory.getClassInstrumentation(CallLoggerFactory.java:108) at com.google.testing.threadtester.Instrumentation.getClassInstrumentation(Instrumentation.java:65) at MyTest.testThreadWeaver(MyTest.java:92

我按照官方 Google 代码网页上的说明进行操作,但似乎不起作用。有什么想法吗?

最佳答案

ThreadWeaver 需要检测您的类以便向您的方法添加断点。因此,您不能直接使用 JUnit 运行测试,而必须从特定的测试运行程序运行测试。对于您的情况,这将是 ThreadedTestRunner。然后,实际的测试方法必须使用 @ThreadedTest 而不是 @Test 进行注释。这应该有效:

@Test
public void startTest() throws Exception {
new ThreadedTestRunner().runTests(getClass(), Example.class);
}

@ThreadedTest
public void testThreadWeaver() throws Exception {
// here comes your test
}

关于java - ThreadWeaver 总是抛出 IllegalArgumentException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21514255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com