Sweety Bertilla
Sweety Bertilla

Reputation: 1032

How to mock the return data in the unit test

I have the below code

Class A {
    public boolean showData() {
        NewData data = getNewData();
        if (data!=null) {
            return true;
        } else {
            return false;
        }
    }

    public NewData getNewData () {
        return NewData = abc;
    }
}

I need to mock getNewData to return the mocked data, when I call showData().

To be clear,

if I mock the getNewData like below,

when(a.getNewData()).thenReturn(null);
assertFalse(showData()) // this doesn't work because the mocked internal getNewdata is not used.

is there a way to fix this?

Upvotes: 0

Views: 107

Answers (2)

Dirk Herrmann
Dirk Herrmann

Reputation: 5939

Assuming you want to test A.showdata, you can derive a class from A that overrides getNewData which returns whatever you need for testing. It's a technique known as 'subclass and override'.

EDIT: In pseudocode, you do the following:

Class B: public A {
    public NewData getNewData () {
       return <whatever you need for your test>
    }
}

Now, to test A.showData, you do the following:

B mySut = new B();
Bool result = mySut.showData();  // this calls A.showData, which calls B.getNewData.

Upvotes: 1

8bytewonder
8bytewonder

Reputation: 9

The best way is to inject NewData into the method as a parameter

showData(data) and have the class/method that calls showData use getNewData()

When mocking, dependency injection is the general answer to issues (in my experience). This allows you to pass in the exact NewData you want the method to use and therefore mock.

Upvotes: 0

Related Questions