Nika Kurashvili
Nika Kurashvili

Reputation: 6462

how to mock class in java without creating interface

First, I am not Java developer, I am using php.

I am curious in Java, for example if I have structure like this:

interface Ainterface {
    public String method();
}

public class A implements Ainterface {
    public String method() {
       //do something
    }
}

public class B {
    public String method(Ainterface a) {
       a.method();
       //do something
    }
}

Now if I want to test B's method I can mock a

public class Amock implements Ainterface {
    public String method() {
       //do something
    }
}

And inject it into B's method.

But, if I don't want to create interface and I have situation like this:

public class A {
    public String method() {
       //do something
    }
}

public class B {
    public String method(A a) {
       a.method();
       //do something
    }
}

Is there any way to mock a or test B's method in other way?

Upvotes: 2

Views: 670

Answers (2)

Kartik
Kartik

Reputation: 7917

@m.antkowicz's answer shows the correct way of doing it, by using a mocking framework. In the comments you asked for a way without using external framework, so this answer tries to address that.

Just like you created Amock by implementing Ainterface, you can create a child class that extends A.

So you would have a class like class AmockClassBased extends A and then you can override method() to make it do what you were doing in Amock class's method().

So your Amock will be changed to:-

public class AmockClassBased extends A {

    @Override
    public String method() {
       //do something
    }
}

Then you can pass an instance of this class to B's method(A a).

Upvotes: 1

m.antkowicz
m.antkowicz

Reputation: 13571

In Java you can use specific mocking framework like Mockito and use it's specific method - for example

A aMock = Mockito.mock(A.class);

Of course this way you can only create a really simple mock that will do literally nothing but the framework allows you to define what specific method should return with providing when/then mechanism. The example of such can be

when(aMock.method()).thenReturn("I am just a fake");

The mockito is really powerfull and I cannot explain you whole framework in this answer so please visit Mockito home and reference page to get familiar with this

Also Mockito is one of solutions - it's kind of popular but not only the one so you can look for the solution that fits your requirements best

Upvotes: 4

Related Questions