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 incollection
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 inwriter
. way can pass instringwriter
capture output testing purposes. can add method (e.g.writetofilenamed(string filename)
) encapsulatefilewriter
creation.
Comments
Post a Comment