-2

I am working on Mockito and JUnit integration. For mocking the objects I created some setter method

@Mock
private SomeDaoImplClass someDaoImplClass

jdbcTamplate = Mockito.mock(NamedParameterJdbcTamplate.class)
someDaoImplClass.setNamedParameterJdbcTamplate(jdbcTamplate)

So method setNamedParameterJdbcTamplate(jdbcTamplate) was not there and I created this setter method in class. I got some information that you can't create these set method in business class b'coz its effecting business unit.

Please someone can suggest me how set methods affecting BU.

Rogério
  • 16,171
  • 2
  • 50
  • 63
NewUser
  • 65
  • 1
  • 5
  • I'm not surprised. The spelling police should also have been after you. This is an XY problem. You need to state what you're attempting here, not ask how to get around your organizational policies. – user207421 Jun 20 '17 at 05:55

1 Answers1

0

No business object should allocate its own dependencies (you know, due to that Inversion of Control/Dependency Injection thing)

So if you need to provide something to you objects you can do it either with setters or via constructor (the latter is preferred)

It's true that adding methods just for the sake of testing is a bad practice. In this case it can be even worse: adding a setter prohibit us to make the object immutable which is something desirable when working with multiple threads and adds some security restrictions (no attribute is without initialization after the constructor has finished.

If you need to add these methods document it and set its visibility to default so it's only visible from the same package (the tests will be at that same package) in order to minimize the impact in production

If you can't add a setter or modify the constructor... Well, it's not all lost. You can make use of reflection. By using this you can modify any attribute of your object even without accessors or even final attributes. Notice that this will be slower at runtime and will require some exception handling

Alberto S.
  • 7,409
  • 6
  • 27
  • 46