简体   繁体   English

Java:提取接口仅用于测试

[英]Java: extracting interfaces just for testing

I want to test my code but I am noticing that some business logic classes demand on alot of objects with alot of state. 我想测试我的代码,但我注意到一些业务逻辑类需要很多具有很多状态的对象。 But actually the communication between these classes is limited to 1 or 2 methods. 但实际上这些类之间的通信仅限于1或2种方法。

Is it good style if I create an interface with these 2 methods and in my test just create a mock object which does nothing? 如果我使用这两种方法创建一个接口并且在我的测试中创建一个什么都不做的模拟对象,这是不错的风格?

The code will then have alot more interfaces which are not really needed, that's why I'm not sure if it's a good idea? 然后代码会有更多不需要的接口,这就是为什么我不确定这是不是一个好主意?

Although having interfaces is a good idea, you don't need interfaces to do mocking. 虽然拥有接口是个好主意,但您不需要接口来进行模拟。 EasyMock, Mockito and PowerMock all allow mocking of concrete classes. EasyMock,Mockito和PowerMock都允许模拟具体类。 So given that, you can leave the code as is and use Mockito (my personal favorite) to mock the injected classes. 因此,您可以保留代码并使用Mockito(我个人最喜欢的)来模拟注入的类。

FYI, the mocks shouldn't "does nothing". 仅供参考,嘲笑不应该“无所作为”。 They should be tested with each possible return value and each possible exception thrown. 应该使用每个可能的返回值测试它们,并抛出每个可能的异常。

As long as the interfaces capture important concepts, the more the merrier (imho). 只要接口捕获重要概念,越多越好(imho)。 Down the road, you might even find yourself separating parts of the classes not related to the interface into other classes, or creating alternate implementations, and then they end up more clearly appropriate in the production code. 在未来的道路上,您甚至可能会发现自己将与界面无关的部分类别分离到其他类中,或创建替代实现,然后它们最终在生产代码中更加明确。

As noted in another answer, not all mocking frameworks require interfaces, and if they're really only to enable mocking, you might not need them. 正如另一个答案所指出的,并非所有模拟框架都需要接口,如果它们真的只是为了启用模拟,那么您可能不需要它们。

If your mocks aren't actually doing anything, they might more appropriately be called stubs. 如果你的模拟实际上没有做任何事情,它们可能更适合被称为存根。 Usually, real mocks are used to verify that calls to them are made correctly, and they have a very active role in the tests. 通常,真实的模拟用于验证对它们的调用是否正确,并且它们在测试中具有非常活跃的作用。

Regardless of the testing aspect, if you notice that you only need a few specific methods in several parts of your code, I strongly recommend extracting an interface capturing these methods. 无论测试方面如何,如果您发现在代码的几个部分中只需要几个特定的​​方法,我强烈建议您提取捕获这些方法的接口。 It will clarify your architecture and decrease the coupling of your code (on top of making it easier to test). 它将阐明您的体系结构并减少代码的耦合(除了使其更容易测试)。

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

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