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?

Answers


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.


Need Your Help

Do fancy MVC URLs affect how caching is done?

model-view-controller browser caching

When reading some answers to aquestion on clearing cache for JS files, somebody pointed to this part of the http spec. It basically says that URLS containing a ? should not be pulled from the cache,

Can Java MVC pattern be combined with a delegate pattern?

java model-view-controller delegates

I am currently studying MVC and delegate pattern in one of my classes. I know that the MVC requires 4 classes to make it run. Is it possible to have a delegate combined with an MVC, or is that