Java Mockito:有没有办法伪造一个不存在的类



我想伪造一种不存在的实现接口的新型类

这可能吗?

例如,我有一个接口

public interface Worker {
    boolean execute(Job c);
}

我有一堂课

public class CompositeWorker implements Worker {
    private List<Worker> childWorkers = new ArrayList<>();
    public List<boolean> execute(Job j){
        return childWorkers.stream().map(w -> w.execute(j)).collect(Collectors.toList());
    }
    public addWorker(Worker worker) {
        childWorkers.add(worker)
    }
}

要测试:

public class CompositeWorkerTest {
    private CompositeWorker worker;
    @BeforeMethod
    void setup() {
        MockitoAnnotations.initMocks(this);
        worker = new CompositeWorker();
    }
    @Test
    test_worker() {
         Worker worker_A = mock(Worker.class);
         Worker worker_A = mock(Worker.class);
         Job job = mock(Job.class);
         when(worker_A.execute(job)).thenReturn(true);
         when(worker_B.execute(job)).thenReturn(true);
         worker.add(worker_A);
         worker.add(worker_b);
         List<boolean> results = worker.execute(job);
         //assert results contains true
    }

有没有办法伪造/更改Worker worker_A = mock(Worker.class);实现 Worker 但实际上不存在的 FakeWorker fakeWorker = mock(FakeWorker.class)

不存在,我的意思是没有定义:

public class FakeWorker implement Worker 

我想模拟不同类的原因是因为 Worker Type 是唯一的

public addWorker(Worker worker) {
    childWorkers = childWorkers.stream().filter(w -> w.getClass() != worker.getClass())
                                                     .collect(Collectors.toList());
    childWorkers.add(worker)
}

首先,选择名称,明确什么是被测试的系统(sut(以及什么是模拟依赖项!此外,当使用 .initMocks(( 方法时,在许多情况下你不需要调用 Mockito.mock((,只需将类成员注释为 @Mock!在您的情况下,我建议在您的测试类中创建扩展 Worker 的嵌套类:

public class CompositeWorkerTest {
  interface WorkerA extends Worker {};
  interface WorkerB extends Worker {};
  @Mock
  WorkerA workerAMock;
  @Mock
  WorkerB workerBMock;
  @Mock
  Job jobMock;
  // systemm under test
  private CompositeWorker sut;
  @BeforeMethod
  void setup() {
    MockitoAnnotations.initMocks(this);
    sut = new CompositeWorker();
  }
  @Test
  void test_worker() {
     when(workerAMock.execute(jobMock)).thenReturn(true);
     when(workerBMock.execute(jobMock)).thenReturn(true);
     sut.add(workerAMock);
     sut.add(workerBMock);
     List<boolean> results = sut.execute(jobMock);
     //assert results contains true
  }
}

相关内容

  • 没有找到相关文章

最新更新