Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use mock object in test method implementation

I have a question. There's a method with implementation using another objects. I'd like to test this method which will not using another objects invoking.

class Object1 {

    public void method1() {
        Object2 object2 = new Object2();
        String info = object2.getInfo();
        // ...
        // working with info, which I want to test
        // ...
    }

}

class Object1Test {
    @Test
    public void testMethod1() {
        Object1 object1 = new Object1();
        object1.method(); // want to run this method without invoking Object2
    }
}

Could you help me to understand how in junit while testing method1() can I mock the using of Object2 with something like Object2Mock?

like image 407
wazz Avatar asked Apr 01 '26 02:04

wazz


1 Answers

You need to make some changes to your class to achieve what you are trying to do.

class Object1 {
    private Object2 object2 = new Object2();

    /* Setter Method for Object2 */
    public void setObject2(Object2 object2) {
         this.object2 = object2;
    }

    public void method1() {
        String info = object2.getInfo();
        // ...
        // working with info, which I want to test
        // ...
    }
}

Now you just have to call your setter-method with the mocked object for Object2.

class Object1Test {
    @Test
    public void testMethod1() {
        Object1 object1 = new Object1();
        object1.setObject2(/* Pass your mocked object here */);
        object1.method(); // want to run this method without invoking Object2
    }
}

You can also use Mockito or JMock to create the object mocks. You can simply tell Mockito to return the dummy response whenever getInfo() is invoked on Object2. For example,

Mockito.when(mockedObject2.getInfo()).thenReturn("Dummy Response");
like image 98
user2004685 Avatar answered Apr 03 '26 16:04

user2004685