TPK
TPK

Reputation: 43

Spock - @Subject annotation and util | helper class that's being tested

I got a question regarding convention of tests in Spock.

Let us say we got A class to test, which is util class with static methods. Classic way to test it, would be A.method() in each test method.

However, in Spock we got @Subject annotation (and also Groovy let us do that, even if said class has private constructor) and I began wondering.

@Subject util = new A()

And later in tests we would call the methods by util.method().

By doing that, we would achieve cleaner test. Instantly we see what's being tested. In most IDEs it would be highlighted and so. @Subject is very verbose annotation.

Do you see any cons of doing tests such a way? Or there is any better way to clealny test util classes in Spock?

Upvotes: 4

Views: 2389

Answers (1)

Michal Kordas
Michal Kordas

Reputation: 10925

I see an advantage of having verbose @Subject, but instantiating utility class can cause much more confusion.

There is check it IntelliJ about instantiation of utility class:

Reports any new expressions which instantiate utility classes. Utility classes have all fields and methods declared static, and their presence may indicate a lack of object-oriented design. Instantiation of such classes most likely indicates programmer error.

  • It's unnatural and might be considered as programming mistake by other developers
  • Disobeying private keyword is bad practice
  • Sonar, CodeNarc and IntelliJ will most definitely complain

I would go with classic approach or avoiding utility classes at all. It's all about convention though.

Upvotes: 3

Related Questions