Post by Ted YuHi,
public boolean isFileClosed(Path f) throws IOException{
try {
isFileClosedMeth =
dfs.getClass().getMethod("isFileClosed",
new Class[]{ Path.class });
} catch (NoSuchMethodException nsme) {
LOG.debug("isFileClosed not available");
} finally {
findIsFileClosedMeth = false;
}
You seem to be confused as to what is being tested and what needs to be
mocked.
Are you testing the "application" code above to see if can detect this
"duck typing"?
If so, make sure this routine is somewhere you can test it separately
That routine needs some style improvements for readability and testability
I would write a separate routine
public boolean hasIsFileClosedMethod(Object duck) {
try {
isFileClosedMeth =
duck.getClass().getMethod("isFileClosed",
new Class[]{ Path.class });
} catch (NoSuchMethodException e) {
return true;
} finally {
return false;
}
}
Now you can test this method
you can always use it in some other routine to set flags and set members
or local variables.
...
if (hasIsFileClosedMethod(myObject) {
... flag = true;
} else {
... log. ...
flag = false;
}
Note: your sample code always sets the flag to false. I think you
mis-used final.
So to test
1. Create an Application (assuming that is the object which has the
above code and now my new and improved separate method to do this work)
2. Test case 1: call the method with an object that has such a routine.
assertTrue( app.hasIsFileClosed( new Object() {
public boolean isFileClosed(Path f) { return false } }
);
I probably just confused you jamming it all in one statement with an
anoymous inner class, and Steve L. will point out it helps to name
things, so you could write the sample class which has the right method
right in the unit test as a nested class.
static class AClassThatHasIsFileClosedMethod {
public boolean isFileClosed(Path f) { return false }
}
....
assertTrue( app.hasIsFileClosed( new AClassThatHasIsFileClosedMethod()
); // add appropriate expectation message to assert
3. Test case 2: call the method to test with an object that does NOT
have the routine.
assertFalse( app.hasIsFileClosed( new Object()); // add appropriate
expectation message to assert
no mocking involved.
I'd also wonder why you'd ever not know that you are working with an
object without such a specialized method.
Why aren't there the right set of interfaces and super classes and the
use of inheritance such that polymorphism is your friend?
What do you do with this information?
Occasionally, very occasionally, I might us instanceof in Java, but
asking about "duck typing" I have never had to do that.
Where did you get this object that you don't know if it has a particular
method?
Hopefully the reason is that you are trapped in a library framework that
didn't allow enough specification (maybe in a generic class) such that
you don't really know at your point in the code what you are looking at,
but I suspicious even then there is not a way out of this through better
coding.
-Paul