Reputation: 1009
I am using ActiveJDBC in my project which has a model ScriptRule
. Please find the attached code snippet.
public class RuleEvaluatorProvider {
public static RuleEvaluatorClient getRuleEvaluatorClient() throws ScriptException, IOException {
List<ScriptRule> scriptRuleList = ScriptRule.findAll();
// some processing
return new RuleEvaluatorClient(someObj);
}
}
I am using PowerMock for writing unit tests. I am facing an issue in testing the method RuleEvaluatorProvider.getRuleEvaluatorClient()
. The findAll()
method returns a org.javalite.activejdbc.LazyList<T>
object.
Therefore, a PowerMockito.when(ScriptRule.findAll()).thenReturn();
wouldn't work because I can only create a utils List. Does anybody have experience doing unit tests like these with ActiveJDBC.
Please help.
Upvotes: 2
Views: 1813
Reputation: 5518
I do not think you need to write this code. In other words, you are mocking something that comes out of the ActiveJDBC model. It is much better to write tests that access a local test database and write/return test records. In other words, I would suggest entering some test records into your local DB, then calling the findAll()
and validating that you have the right data.
Upvotes: 0
Reputation: 140417
Your problem is simply that you have written hard-to-test code there. One way of resolving that is using Powermock. But doing so will not help with the design problems within your production code.
Instead, consider something like this:
interface RuleFinder {
public List<ScriptRule> findAllRules();
}
and a stupid impl like
class RuleFinderImpl implements RuleFinder {
@Override
public List<ScriptRule> findAllRules() { return ScriptRule.findAll(); }
}
Now you can use dependency injection to provide some object implementing that RuleFinder interface into your production code. And the key thing there: at runtime, that object is simply an instance of that impl class, that calls that static method in ScriptRule.
But for testing, you can inject a mocked object.
And for the final call to new; you would be using a factory, again with dependency injection.
That is how you write testable, well-decoupled production code. Versus writing hard-to-test production code and using the heavy Powermock hammer to "fix" your deficient design!
For more information on "writing testable code", just watch those videos.
Upvotes: 2