Too many dependencies in Mocking: Unit test question

I want to run a business class test, and I have this problem: one of the mocking objects has many dependencies on other classes such as Sites, URLs and ComplexObject.

My question is: how can I isolate my class if I need to use this method of my layout in the method I need to check? Should I mock them and add them to the mocked object?

+4
source share
2 answers

How else can you test it? It sounds like you need to mock addictions. One positive aspect is that you can probably use layouts in other classes that need testing. Please note that this is a certain smell of code .

Have you ever thought about dependency injection ? If you passed all the dependencies, you could create a factory that generates a set of test dependencies, and then overrides only the dependencies needed for your test.

+4
source

What I like to do is create a class that has a field for all external dependencies, as well as static methods. eg:

public class DanceMakerDependecies{ private URL url; public String getCurrentUser(){ // not static, so very easy to test return UserManager.currentUser().getName(); } //getter and setters } public class DanceMaker{ public DanceMaker(DanceMakerDependecies dep){ .. } // you could also create default constructor with the default dependencies } public class DanceMakerTest{ @Test void dance(){ DanceMaker dm = new DanceMaker(); dm.setDependecies(EasyMock.createMock(DanceMakerDependecies.class)); //etc. } } 

I know that purists would prefer to just put everything in a class, but I find this way of testing a lot simpler. try it and see what you think about it (I put it not the best, or a design template, but I like it).

0
source

Source: https://habr.com/ru/post/1337506/


All Articles