Skip to content

Instantly share code, notes, and snippets.

@btforsythe
Created October 6, 2017 21:13
Show Gist options
  • Save btforsythe/cd3e77a2b3b5c3e4a478d38f23fa22d7 to your computer and use it in GitHub Desktop.
Save btforsythe/cd3e77a2b3b5c3e4a478d38f23fa22d7 to your computer and use it in GitHub Desktop.
Examples of testing abstract class in Java
package virtualpet;
public class Dog extends VirtualPet {
public Dog(String name) {
super(name);
}
@Override
public void tick() {
// do tick stuff
}
}
package virtualpet;
public abstract class VirtualPet {
private String name;
public String getName() {
return name;
}
public VirtualPet(String name) {
this.name = name;
}
public abstract void tick();
}
package virtualpet;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
* Examples of different ways of creating the object under test when the class
* is abstract, but we want to test the concrete bits of it.
*/
public class VirtualPetTest {
@Test
public void shouldAssignNameUsingAnonymousInnerClass() {
VirtualPet underTest = createAnonymousTestInstance("Fido");
/*
* same as assertEquals("Fido", underTest.getName()), but more expressive and
* less prone to error
*/
assertThat(underTest.getName(), is("Fido"));
}
private VirtualPet createAnonymousTestInstance(String name) {
return new VirtualPet(name) {
@Override
public void tick() {
// empty -- we're not testing this method
}
};
}
/**
* It can be very verbose to use anonymous inner classes, so sometimes a fake
* implementation is cleaner. Also, they may be easier to grasp for the
* unfamiliar.
*/
@Test
public void shouldAssignNameUsingTestSubclass() {
VirtualPet underTest = new TestVirtualPet("Fido");
assertThat(underTest.getName(), is("Fido"));
}
private class TestVirtualPet extends VirtualPet {
public TestVirtualPet(String name) {
super(name);
}
@Override
public void tick() {
// empty -- we're not testing this method
}
}
/**
* This may well be the best way -- create a concrete instance. This is not
* always possible (or desirable) in the wild, since there may be side effects
* or overhead or simply shite code.
*/
@Test
public void shouldAssignNameUsingConcreteSubclass() {
VirtualPet underTest = new Dog("Fido");
assertThat(underTest.getName(), is("Fido"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment