作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想伪造一个不存在的实现接口(interface)的新类
这可能吗?
比如我有一个接口(interface)
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
之所以要mock一个不同的class是因为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
}
}
关于java模拟: is there a way to fake a class that doesnt exists?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55525944/
我是一名优秀的程序员,十分优秀!