lundi 2 mars 2015

Is it bad practice to make a method package or private for the sake of testing?

In Java (in an Android specific context, but this should apply across the board), is it considered bad practice to remove a private modifier - and thus be package specific - for the sake of unit testing?


Say I have something like the following:



public void init(long id) {
mId = id;
loadItems(1);
}

public void refresh() {
loadItems(mId);
}

private void loadItems(int page) {
// ... do stuff
}


In this case, I have 2 public methods that should definitely be tested. The concern is that both the refresh() and init() methods are almost identical minus some logic around handling the id.


It seems like it'd be easiest to write a unit test for loadItems() and then just verify that both init() and refresh() call loadItems() with the appropriate id (using something like Mockito). There's not a "good way" to test private methods though.


Would doing that make me a bad software developer? I know private methods technically shouldn't need unit tests, but this would be a straightforward testing approach, IMO, especially if loadItems() is somewhat complex.


Aucun commentaire:

Enregistrer un commentaire