简体   繁体   English

如何在Java中测试匿名嵌套类?

[英]How to test anonymous nested class in java?

I need check with junit that method of nested anonymous class invoked. 我需要检查与junit嵌套的匿名类的方法被调用。 But this class is private. 但是此类是私人的。 Does there exist a way to test it without changing visiblity and logic of work? 有没有一种方法可以在不改变工作可见性和工作逻辑的情况下对其进行测试? It may be that a common way exists to resolve similar problems? 可能存在解决类似问题的通用方法吗?

The fact that the class is private or anonymous means that the implementation details are private. 该类是私有或匿名的事实意味着实现细节是私有的。 In general, your tests should not be depending upon implementation details, but should be testing behaviour , not the specific implementation. 通常,您的测试不应取决于实现细节,而应取决于测试行为 ,而不是特定的实现。

The only way is to test the method that creates the object of the anonymous inner class, or to make it non-anonymous and non-private. 唯一的方法是测试创建匿名内部类的对象的方法,或使其成为非匿名和非私有的。 (I've seen a fair amount of code that makes it default-visibility and uses a @VisibleForTesting annotation.) (我看过很多代码,使其具有默认可见性并使用@VisibleForTesting注释。)

You should not test that private class directly. 您不应该直接测试该私有类。

Most likely it's just a small class used as a util or it implements some broad, public interface. 它很可能只是一个用作util的小类,或者它实现了一些广泛的公共接口。

In the first case just test class that wraps up the private class, and don't worry about private one at all. 在第一种情况下,只是测试类包装了私有类,根本不用担心私有类。 You can treat it as an implementation detail. 您可以将其视为实现细节。

In second case just test that class against it public interface. 在第二种情况下,只需针对其公共接口测试该类。

If I'm wrong about your code, then my advise would be to change design a bit, move wrapper class into separate package, extract private class to package level and test it directly. 如果我对您的代码有误,那么我的建议是稍作更改设计,将包装器类移到单独的程序包中,将私有类提取到程序包级别并直接对其进行测试。 Last way would be to mark it as @VisibleForTesting (annotation from Guava library) and raise visibility to package private (default). 最后一种方法是将其标记为@VisibleForTesting(来自Guava库的批注),并提高包私有性的可见性(默认)。

I quite agree with Matthew Farwell when he says: 我非常同意Matthew Farwell的话:

In general, your tests should not be depending upon implementation details, but should be testing behaviour, not the specific implementation. 通常,您的测试不应取决于实现细节,而应是测试行为,而不是特定的实现。

However, tests call out for good design. 但是,测试要求好的设计。 If you really feel you should test that class directly, then that's a hint that that class should be a normal public class (and not an inner anonymous). 如果您真的觉得应该直接测试该类,则表明该类应该是普通的公共类(而不是内部匿名类)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM