java - How to test void method in JUnit -


this question has answer here:

how test void method using junit.

void add(int a, int b) {  int c= + b; } 

how test above method using junit in java.

if method has side effects, can check them in junit test.

in example, method has no side effects, there nothing test.

if still want test it, can use reflection so, don't think practice.

you can check junit faq related section:

how test method doesn't return anything?

often if method doesn't return value, have side effect. actually, if doesn't return value , doesn't have side effect, isn't doing anything.

there may way verify side effect occurred expected. example, consider add() method in collection classes. there ways of verifying side effect happened (i.e. object added). can check size , assert expected:

@test public void testcollectionadd() {     collection collection = new arraylist();     assertequals(0, collection.size());     collection.add("itema");     assertequals(1, collection.size());     collection.add("itemb");     assertequals(2, collection.size()); } 

another approach make use of mockobjects.

a related issue design testing. example, if have method meant output file, don't pass in filename, or filewriter. instead, pass in writer. way can pass in stringwriter capture output testing purposes. can add method (e.g. writetofilenamed(string filename)) encapsulate filewriter creation.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -