문제

I've been utilizing stub implementations of my abstract classes for testing purposes. Currently, my unit tests are residing in a test directory alongside my src directory.

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.
  • 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.
  • Keeping the stub classes somewhere in the test package structure. 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.

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.


It might be worth knowing that a lot of projects evolve to have "Builder" objects that work like this:

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. Having just one PersonStub may not be enough.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top