user1312312
user1312312

Reputation: 635

Junit using Mock Objects

MyClass{

public void myfunction(){
AnotherClass c=new AnotherClass();
c.somethod();//This method sets some values of the AnotherClass object c;

}
}

I have the above scenario to be tested.How do I check if the value of AnotherClass Object c is set properly.I understand that I have to use Mock Objects for these.But couldn't figure out how because here I cannot pass the mock object of AnotherClass to myfunction because of the above design.Can anybody help me?

Upvotes: 2

Views: 6816

Answers (1)

Dev Blanked
Dev Blanked

Reputation: 8865

if you really want to do this should do a redesign like follows (as Dan has also suggested)

import org.junit.Test;
import org.mockito.Mockito;

public class TestingMock {

    @Test
    public void test() {
        MyClass target = Mockito.spy(new MyClass());
        AnotherClass anotherClassValue = Mockito.spy(new AnotherClass());
        Mockito.when(target.createInstance()).thenReturn(anotherClassValue);
        target.myfunction();
        Mockito.verify(anotherClassValue).somethod();
    }

    public static class MyClass {

        public void myfunction(){
            AnotherClass c = createInstance();
            c.somethod();//This method sets some values of the AnotherClass object c;
        }

        protected AnotherClass createInstance() {
            return new AnotherClass();
        }
    }

    public static class AnotherClass {

        public void somethod() {

        }

    }
}

You will see that commenting out c.somethod() makes the test fail. I'm using Mockito.

Upvotes: 2

Related Questions