I have a Java class that simply extends a library class and calls a method of its parent with a default parameter. How do I write a Junit test for that? A MockObjectTestCase is good too. Here is an example of what I'm talking about:
public class ResourceBundleMessageSource {
public String getMessage(String key, Object[] objects, Locale locale) {
//Spring library method
}
}
public class MessageResource extends ResourceBundleMessageSource {
public String getMessage(String key) {
return (getMessage(key, null, Locale.getDefault());
}
}
I know the wrapper method isn't even necessary, but makes frequent calls to it easier. Note the class works fine, I'm only interested in how the unit test is written.
If you would be willing to refactor your class slightly, I would recommend MessageResource delegate to a MessageSource instance, rather than extend ResourceBundleMessageSource. Then I'd use mocks in my unit test. Something like this:
public class MessageResource implements MessageSource {
private final MessageSource delegate;
public MessageResource(MessageSource delegate) {
this.delegate = delegate;
}
public String getMessage(String key) {
return delegate.getMessage(key, null, Locale.getDefault());
}
// need to implement three other MessageSource methods,
// simple pass-throughs to delegate
}
and unit test
public class MessageResourceTest {
private MessageSource mockDelegate;
private MessageResource messageResource;
@Before
public void setUp() throws Exception {
mockDelegate = //mock with your favorite framework, or by hand
messageResource = new MessageResource(mockDelegate);
}
@Test
public void testGetMessage() {
String key = "foo";
String actualMessage = messageResource.getMessage(key);
assertEquals(key, /* get key passed to mock delegate */ );
assertSame(Locale.getDefault(), /* get Locale passed to mock delegate */);
assertEquals(/*expected message from mock*/, actualMessage);
}
}
For this particular example I probalby would not bother to test it.
If you do need to test it, try something like:
@Test
public void getDefaultMessage() {
ResourceBundleMessageSource origSource = <create source>
MessageResource subSource = <create with same criteria as origSource>
String key = <some key that is locale-specific>
assertEquals(origSource.getMessage(key, null, Locale.getDefault()),
subSource.getMessage(key));
}
If the first two lines are hard to write, then it makes even more sense not to test it. If you have several tests like this, move the first two lines into a setup fixture.
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