我想伪造一个不存在的实现接口的新型类
这可能吗?
例如,我有一个界面
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)
}
答案 0 :(得分:1)
首先,选择可以清楚说明正在测试的系统(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
}
}