I need to write a test for a class that extends an abstract class. Problem starts when I need to test a method that has super reference. So the code looks something like this:
public abstract class AbstractClass{
public String someMethod();
}
public class MyClass extends AbstractClass {
methodToTest(){
//somecode
super.someMethod();
}
}
Any idea how should I get around it?
EDIT:
I'm sorry, I am still new to unit testing and just a moment ago figured out why exactly this is not working as I would like to. MyClass in the example above actually contains a initialization block that sets some fields declared in AbstractClass that are used by someMethod so new AbstractClass.someMethod() didn't give me the same results as super.someMethod. And, as I cannot initialize the AbstractClass it would be impossible to get desired results. I figured that I would need to mock it somehow but as I said I am new to this and have no idea how to do that
public abstract class AbstractClass{
String fieldA;
public String someMethod(){
//does something with fieldA
}
}
public class MyClass extends AbstractClass {
{
setFieldA("something");
}
methodToTest(){
//some code
super.someMethod();
//returns some string based on the fieldA value
}
}
UPDATE Here is updated version of my code. Please help me with writing test for that. I would probably be able to get it from there:
public abstract class AbstractClass{
String fieldA;
public String someMethod(){
fieldA = "String" + fieldA;
}
}
public class MyClass extends AbstractClass {
{
setFieldA("Another String");
}
methodToTest(){
fieldA = fieldA + "Yet Another String";
super.someMethod();
return fieldA;
}
}
Your problem is less about unit testing; but more a general misconception how to work with abstract classes.
First of all: if your abstract class needs a field to do its job, then you better not use a setter for that. Instead:
public abstract class Base {
private final String thatField;
public Base(String incoming) {
thatField = incoming;
}
..
public class Derived extends Base {
public Derived(String incoming) {
super(incoming);
}
In other words: it seems that this field is an important part of your classes. So make that explicit. And by enabling it to be set via constructor, you also ensure that
you control when/how the field gets set
you get help from the compiler - by making the field final, you get errors when you forget initializing
Beyond that: when you start testing some class ... it shouldn't matter if that class just extends Object; or if it extends some other class; even when extending an abstract class.
That is about what can be said here; given the fact that your example doesn't contain any specific details about what your code is "really" doing.
Related
I have a problem to chose the between an abstract class without abstract methods OR a base class with an interface.
I have two implementation in my mind:
1.
Let's say I have a AbstractRenderer:
abstract class AbstractRenderer
{
protected $shape;
public function __construct(AbstractShape $shape)
{
$this->shape = $shape;
}
public function render(): string
{
return $this->shape->generate()->asArray();
}
}
and the WebRenderer would be like this:
class WebRenderer extends AbstractRenderer
{
}
2.
Have a base class and an interface like this:
Interface InterfaceRenderer
{
public function __construct(AbstractShape $shape);
public function render(): string;
}
and a base class that impediments the interface:
class BaseRenderer implements InterfaceRenderer
{
protected $shape;
public function __construct(AbstractShape $shape)
{
$this->shape = $shape;
}
public function render(): string
{
return $this->shape->generate()->toString();
}
}
again, my WebRenderer would be like this:
class WebRenderer extends BaseRenderer
{
}
I don't know which is the correct implementation, or there is a better way to implement this and what is the pros and cons of each.
Thanks
From the Renderer client’s perspective the 2 solutions are basically identical. As long as they depend on an abstract object (interface or an abstract class), you’ll have benefits of polymorphism. You’d lose those if you make them depend on WebRenderer (concrete object).
Interface’s benefits over abstract classes
doesn’t occupy inheritance
no fragile base class problem
Abstract classes provide
static methods (in many languages interface can’t have these)
protected implementation
I know that it is possible to base class variable holding derived class object. Like below....
class Animal
{
public void printName()
{
System.out.println("Print your name");
}
}
public class Tiger extend Animal
{
public void Print()
{
System.out.println("My Name");
}
public void static main(String args[])
{
Animal type1 = new Tiger();
//with this new created type1 varibale. I can only access members of Animal class.
type1.PrintName() // valid
type1.Print() //In-valid
}
}
So what is the usefulness of this? Still I don't see any benefit. Can someone explain me, may be I am missing something. Thanks.
In this case, where the variable is initialized from a child class variable, it isn't terribly useful. The usefulness comes in two cases:
When you have a function parameter with a base class type and you pass in a child class object as the actual argument.
void CareForAnimal(Animal anm) {
anm.Feed();
anm.Sleep();
}
While it's technically possible to allow you to do things with formal parameters you can't do with regular variables, as a language designer it's a lot of complication to make them different for not a lot of benefit.
When you have a base class variable initialized from the result of a method which is itself virtual:
Animal Breed(Animal father, Animal mother) {
Animal child = mother.mater(father);
child.Bathe();
child.Nurse(mother);
return child;
}
Now, you don't know right away which child class child is being initialized with.
i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.
Let's say that class A is abstract and defines read-only properties that class B, which inherits from it, must provide. Is it better practice to define such properties as abstract or as set-protected:
public abstract class A
{
public abstract int Value { get; }
}
public class B : A
{
public override int Value { get { return 1; } }
}
OR
public abstract class A
{
public int Value { get; protected set; }
}
public class B : A
{
public B()
{
Value = 1;
}
}
I think that the first solution is probably better but i'd like to hear other opinions.
It depends on what you mean by read-only. If you mean read-only for callers, then I would prefer the second solution.
The first solution forces the child class to implement get, which is good. But it prohibits the child from implementing set (even a protected one), which is bad.
With the second solution, the whole Value interface is defined by the base class, which is good, and the child class is still able to set Value when it chooses, which is also good.
If on the other hand by "read-only" you mean truly read-only, in that not even the child class is allowed to set Value, then the first solution is better. You even get the right compile error if you do try to set it.
Suppose the following (slightly pseudo-code for brevity):
class Basic
{
String foo;
}
class SomeExtension extends Basic
{
String bar;
}
class OtherExtension extends Basic
{
String baz;
}
class BasicService
{
Basic getBasic()
{
}
}
class SomeExtensionService extends BasicService
{
SomeExtension getSomeExtension()
{
}
}
class OtherExtensionService extends BasicService
{
OtherExtension getOtherExtension()
{
}
}
What would be the most idiomatic, elegant way to implement the get-() service methods with the most possible code reuse?
Obviously you could do it like this:
class BasicService
{
Basic getBasic()
{
Basic basic = new Basic();
basic.setFoo("some kind of foo");
return basic;
}
}
class SomeExtensionService
{
SomeExtension getSomeExtension()
{
SomeExtension someExtension = new SomeExtension;
Basic basic = getBasic();
someExtension.setFoo(basic.getFoo());
someExtension.setBar("some kind of bar");
return someExtension;
}
}
But this would be ugly if Basic has a lot of properties, and also you only need one object, as SomeExtension already inherits Basic. However, BasicService can obviously not return a SomeExtension object.
You could also have the get methods not create the object themselves, but create it at the outermost level and pass it to the method for filling in the properties, but I find that too imperative.
(Please let me know if the question is confusingly formulated.)
EDIT: Okay, so it was. I'll try to explain it better. Say you have two model classes, A and B. You also have two classes for returning objects of class A and B (from a database for instance, with information scattered all over so any ORM doesn't apply). Now, say A and B contains a lot of overlapping information, so it makes sense to refactor into a superclass C and let A and B extend from it. However, the service classes are still particular to A and B and need to duplicate the code for reading the overlapping information. How could you refactor these into a service class C?
I would add constructor to A and B which accepts C and sets the fields accordingly. The advantage over your suggested solution is that your ExtensionServices don't have to know about basic fields.
It looks like you're setting default values to your Basic (and children) objects. It's probably best to do that in their constructors.
public class Basic
{
protected String foo;
// and other properties
public Basic()
{
foo = "some kind of foo";
// assign defaults to all other properties
}
}
public class SomeExtension extends Basic
{
protected string bar;
public SomeExtension()
{
super(); // set the default properties of the base class
bar = "some kind of bar";
}
}
Remember to call super() in the child constructors so that the inherited properties will also be assigned default values.
public class BasicService
{
public Basic getBasic()
{
return new Basic();
}
}
public class ExtensionService extends BasicService
{
#Override
public Basic getBasic()
{
return new SomeExtension();
}
}
At least with this structure, you eliminate having to instantiate two objects in ExtensionService, and you actually don't set default values in the service classes. Since SomeExtension is a child of Basic, you can return a SomeExtension at the end of a function whose declared return type is Basic.