我们有一堆类监听来自服务器的事件,然后对它们做出响应。 例如:
class EventManager { private Set<Event> cache = new HashSet<Event>(); private EventListener eventListener = new EventListener() { void onEvent(Event e) { if (e instanceof MyEvent || e instanceof YourEvent) { handleEvent(e); } } } public EventManager(ServerCommunication serverComm) { serverComm.addListener(eventListener); } private handleEvent(Event e) { // handle the event... // ... cache.add(cache); // ... } }这是我们正在做的事情的一个典型例子。 以下是我看到的问题:
我想测试handleEvent以确保它正在做它应该做的事情,但我不能,因为它是私有的。 我还想检查一下是否有东西被添加到缓存中,但这似乎也很困难,因为缓存是私有成员,我不想添加一个不必要的getter方法。 我还想测试匿名类的onEvent方法中的代码。现在,我所做的是将所有逻辑从匿名类移到handleEvent方法,并使handleEvent包为private(我的单元测试在同一个包中)。 尽管我想要,但我并未检查缓存的内容。
有没有人对更可测试的更好的设计有任何建议?
We have a bunch of classes that listen for events from the server and then respond to them. For example:
class EventManager { private Set<Event> cache = new HashSet<Event>(); private EventListener eventListener = new EventListener() { void onEvent(Event e) { if (e instanceof MyEvent || e instanceof YourEvent) { handleEvent(e); } } } public EventManager(ServerCommunication serverComm) { serverComm.addListener(eventListener); } private handleEvent(Event e) { // handle the event... // ... cache.add(cache); // ... } }Here's a made-up example of the kind of thing we are doing. Here are the problems I see:
I'd like to test handleEvent to make sure it's doing what it is supposed to but I can't because it's private. I'd also like to check that something got added to the cache too but that also seems difficult since cache is a private member and I don't want to add a needless getter method. I'd also like to test the code inside the anonymous class's onEvent method.For now, what I did was move all logic from the anonymous class to the handleEvent method, and I made handleEvent package private (my unit test is in the same package). I'm not checking the contents of the cache although I want to.
Does anyone have any suggestion for a better design that is more testable?
最满意答案
我可能会提取一个EventCache组件。 您可以使用实现计算缓存事件或记录任何感兴趣的内容来替换此测试。
我可能不会改变handleEvent的可见性。 您可以实现只从测试用例中引发事件的ServerCommunication。
I would probably extract a EventCache component. You can replace this for your test with an implementation that counts the cached events or records whatever is of interest.
I probably would not change the visibility of handleEvent. You could implement a ServerCommunication that just raises the event from the test case.
更多推荐
发布评论