java - Is it a good approach to override methods in a class which you don't want to test? -


suppose class has 3 methods:

public void parent() throws exception {} public string child_1(string arg_1) throws ioexception {} public boolean child_2(string arg_1, string arg_2) throws sqlexception {} 

parent() calls child_1() , child_2(), like:

public void parent() throws exception {     // complicated stuff      child_1("str1");      // more stuff      child_2("str1", "str2");      // more stuff } 

now, if have tested child_1() , child_2() , want test parent(), ok override child_1() , child_2() , test parent()? this:

myclass myclass = new myclass() {     @override     public string child_1(string arg_1) throws ioexception {         return "expected_string_to continue_execution";     }      @override     public boolean child_2(string arg_1, string arg_2) throws sqlexception {         return true;    // return expected boolean result continueexecution;     } };  myclass.parent(); 

by doing this, can test parent() , since child_1() , child_2() tested in other unit tests class, not cheating (atleast that's think, please correct me if wrong). also, in real world, if chaild_1() , child_2() doing complicated, approach makes testing easy, not redundantly check time consuming code.

my question is, whether right approach? if not, downside , importantly, right approach? if can explain same above example, awesome.

thanks lot.

i overriding methods should avoid in general since violates liskov substitution principle. test code no special: should follow same strict principles production code. exception can think of if testing legacy code high coupling between components , overriding option. when writing new code don't see reason.

i think @samlewis on something: if feel want test parent() in isolation reason, child_1() , child_2() should in own classes injected parent(). avoid testing smaller class. if need test smaller have responsibility wants extracted (single responsibility principle).

a hint child_1() , child_2() belongs in other classes public , public method parent() calls it. public methods should typically call non-public methods (although there exceptions).

or did make child methods public can test them? if so, have @ this answer.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -