I often work with methods that accept callbacks, and callbacks seem somewhat difficult to test. Consider the following scenario, if there is a method that accepts a callback using one method (for simplicity, I assume that the test method is synchronous), the following template template can only be written to provide a callback method call:
@Test public void testMethod() { final boolean[] passed = {false}; method(new Callback() { @Override public void handle(boolean isSuccessful) { passed[0] = isSuccessful; } }); assertTrue(passed[0]); }
He looks like a surrogate. I would like to know: is there a more elegant way to test such code so that the code above looks more like the pseudo code below?
@Test public void testMethod() {
A bit cleaner. Is this possible in JUnit, TestNG, or any other testing framework? Thank you
UPDATE
Sorry, I seem to have asked a vague question that really doesn't match what I wanted to ask. I basically meant any code (not necessarily a callback) that can be called if certain conditions are satisfied only to set the state of the result to true. Simply put, I just want to get rid of the initial boolean[] passed and the final assertTrue(passed[0]) , assuming that they are a kind of prologue and epilogue, respectively, and assume that the initial state is set to false , so pass() should be called to set the state to true . No matter how passed[0] set to true , no matter where it comes from. But unfortunately, I asked this question using the callback context, however this is just an option, not a requirement. Thus, the title of the question does not reflect what I really wanted to ask, but the answers were sent before the update.
source share