JMockit:如何将MockUp类注入到测试类中?

时间:2015-09-28 17:33:54

标签: java unit-testing junit dependency-injection jmockit

我是JMockIt的新手,我正试图找出/理解如何将@Injectable用于我已定义的顶级MockUp类。

例如:

// JUnit Test Class
public class RepositoryTest {

    @Tested private Repository repository;
    @Injectable private ResultsAPIWrapper resultsApiWrapper;

    @Test
    public void testRepo(){
        new ResultsApiWrapper();
        assertThat(repository.doSomething(), is("done" ) );
    }
}


// Class under test
public class Repository{

   @Autowired private ResultsAPIWrapper resultsApiWrapper;

   public String doSomething(){
      return resultsApiWrapper.load();
   }
}

// Mocked implementation of the ResultsAPIWrapper that I want injected into Repository
public class ResultsApiWrapperMock extends MockUp<ResultsAPIWrapper>{
   @Mock
   public String load(){
      return "done";
   }
}

如果我尝试以上操作,我会收到错误

java.lang.IllegalArgumentException: Class already mocked: com.fw.wrappers.ResultsAPIWrapper
    at com.fw.wrappers.mock.ResultsApiWrapperMock.<init>(ResultsApiWrapperMock.java:12)
    at com.fw.repository.RepositoryTest.testRepo(RepositoryTest.java:38)

但是如果我删除了new ResultsApiWrapper(),那么我不知道如何指定哪个类是我想要用作autowire的模拟实现。

我是否误解了如何做到这一点?如何指定我希望JMockit使用我的MockUp<>实现进行自动装配?

1 个答案:

答案 0 :(得分:0)

我也是新人,但我觉得这样的事情对你的情况有用...... 这将模拟ResultsAPIWrapper()并且不初始化任何静态变量并为load()创建特定的模拟:

delay(1000)