简体   繁体   English

我将存根放在哪里?

[英]Where do I put my stubs?

I've been utilizing stub implementations of my abstract classes for testing purposes. 我一直在将abstract类的存根实现用于测试目的。 Currently, my unit tests are residing in a test directory alongside my src directory. 目前,我的单元测试位于src目录旁边的test目录中。

I'm wondering if there is a best-practice for where to place any stubs that are used in the testing. 我想知道是否有最佳实践来放置在测试中使用的任何存根。 I have been trying several things, but part of me seems to be perpetually perturbed no matter what I do. 我一直在尝试一些事情,但是无论我做什么,我的一部分似乎总是被打扰。

Things I have tried: 我尝试过的事情:

  • Declaring the stub implementations within the actual unit tests using them. 在使用它们的实际单元测试中声明存根实现。 This falls flat when you have to use the stub in multiple JUnit classes. 当您必须在多个JUnit类中使用存根时,这种情况变得很平坦。
  • Placing the stubs into the same package as their parent class. 将存根与其父类放在同一包中。 This seems like a terrible idea since it suddenly features test code polluting the packages in src . 这似乎是一个可怕的主意,因为它突然具有测试代码,污染了src的软件包。
  • Keeping the stub classes somewhere in the test package structure. 将存根类保留在test包结构中的某个位置。 This seems like the most reasonable option, but I am not sure what the best way to do this is. 这似乎是最合理的选择,但我不确定实现此目的的最佳方法是什么。

Bear in mind, I am probably over-thinking this. 请记住,我可能对此考虑过度。 Is there any information on best-practices that could put my mind to rest? 是否有关于最佳做法的任何信息可以让我安心? Is switching to a mock framework a solution to this dilemma? 切换到模拟框架是否可以解决这个难题?

Much appreciated. 非常感激。

The 3rd option is definitely better than the other two for the reasons you've given. 由于您给出的原因,第三个选项肯定比其他两个选项更好。 I like to refer to the Maven directory structure during times like this , and it doesn't seem to imply anything different than your 3rd option. 我喜欢在这样的时间引用Maven目录结构 ,它似乎并不意味着与您的第三个选项有所不同。

What I do is create the stub as an inner class inside the test itself. 我要做的是在测试本身内部将存根创建为内部类。 Once this gets too messy or needs to be reused, I put the stubs in the same package as the abstract class, but under the test directory. 一旦太混乱或需要重用,我将存根与抽象类放在同一包中,但放在test目录下。


It might be worth knowing that a lot of projects evolve to have "Builder" objects that work like this: 可能值得一提的是,许多项目演变为具有“ Builder”对象,其工作方式如下:

Person person = new PersonBuilder().withName("John Doe").withDefaultAddress().build();

The reason you do this is because sometimes a Person needs to be created lots of different ways depending on what you're testing. 这样做的原因是,有时根据您要测试的内容,需要为Person创建许多不同的方式。 Having just one PersonStub may not be enough. 仅拥有一个PersonStub可能还不够。

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

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