ThreadWeaver总是抛出IllegalArgumentException

时间:2014-02-02 18:11:11

标签: java multithreading unit-testing thread-weaver

我正在尝试使用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:未检测类示例     在   com.google.testing.threadtester.CallLoggerFactory.getClassInstrumentation(CallLoggerFactory.java:108)     在   com.google.testing.threadtester.Instrumentation.getClassInstrumentation(Instrumentation.java:65)     at MyTest.testThreadWeaver(MyTest.java:92

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

1 个答案:

答案 0 :(得分:2)

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
}