I want to unit test a class, Class A
, but it has a dependency on another class that uses a user session
method. The method that I want to test does not involve user session
. Can I make helper method in Class A
that would replicate the behavior of the Class B
method that I need?
I know it's not clear, let's dig some code to get clear understanding....
public void testDetails() throws Exception
{
//Some logic that generates DetailsTOList
saveDetailsHelper(DetailsTOList);
int detailsSize = getDetailsSize();
assertNotNull(detailsSize);
}
Now getDetailsSize()
get size information from a database. Class B
has this method, but I cannot create an object of Class B
and test this method since Class B
gets session information from User, and I can set session information from JUnit class.
I have created saveDetailsHelper
method that replicates behavior of Class B - saveDetails()
method, and am calling that in testDetails()
method as shown above.
My question:
junit class
?JUnit classes function like every other class in java; you're welcome to have helper functions. The only thing that determines whether other functions will be run is (depending on the version of junit) whether or not there is an annotation instructing the harness to run it as a test.
However, this problem is precisely why you should design your classes carefully. If Class B
calls out to a database for information, this is a great opportunity to compartmentalize that functionality. You don't clarify 'dependency' (are you extending?), but if Class B
is a component of Class A, you can create a whole stub class that is a stand in for Class B
, and returns hardcoded (or otherwise coded) data specifically for the testing of class A. As long as the signature of the Class B
proxy is the same, you can have confidence Class A works.
It is often useful to make these inner classes of your test class, to keep things from getting too messy in your workspace.
public class testA {
@Test
public void testDetails {
ClassA a = new ClassA();
a.setDependency(new StubClassB());
//run your test
}
private class StubClassB() extends ClassB {
public boolean saveDetails() {
//return fake information;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With