有“所有者”类。它实现了 ClipboardOwner。所有者在单独的线程中工作并侦听系统剪贴板。当剪贴板的内容发生变化时,所有者会做一些工作。
我为所有者编写了单元测试。我午餐了所有者的线程并更改了剪贴板的内容。调用了 lostOwnership() (我在控制台中看到了消息)。但是间谍没有注意到它。
import java.awt.*;
import java.awt.datatransfer.*;
class Owner extends Thread implements ClipboardOwner {
public Owner(){
super("Owner");
start();
}
@Override
public void run() {
regainOwnership(Toolkit.getDefaultToolkit().getSystemClipboard());
while (true) {}
}
@Override
public void lostOwnership(Clipboard cb, Transferable t) {
//process the change of clipboard's content
regainOwnership(cb);
}
private void regainOwnership(Clipboard cb) {
cb.setContents(cb.getContents(null), this);
}
}
测试类:
import org.testng.annotations.Test;
import java.awt.*;
import java.awt.datatransfer.*;
import static org.mockito.Mockito.*;
public class OwnerTest {
@Test
public void testLostOwnership() throws Exception {
Owner owner = spy(new Owner());
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable t = mock(Transferable.class);
ClipboardOwner newOwner = mock(ClipboardOwner.class);
cb.setContents(t, newOwner);
Thread.sleep(1000);
verify(owner).lostOwnership(cb, t);//test error: Wanted but not invoked
}
}
问题:测试失败,因为间谍没有注意到 Owner#lostOwnership() 被调用。
你怎么看待这件事?谢谢!