如何测试调用私有方法的匿名内部类(How to test an anonymous inner class that calls a private method)

编程入门 行业动态 更新时间:2024-10-28 21:23:12
如何测试调用私有方法的匿名内部类(How to test an anonymous inner class that calls a private method)

我们有一堆类监听来自服务器的事件,然后对它们做出响应。 例如:

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.

更多推荐

本文发布于:2023-07-25 23:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1267554.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部类   测试   方法   test   anonymous

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!