简体   繁体   中英

Define expectations for public final instance variable

I'm new at unit testing and am running into an issue with jMock that I can't seem to figure out. I have a public final instance variable which I need to define an expectation for, but I can't get it to work. If I make a getter for the variable, it works, but I'd rather not have to create a bunch of getters just to make unit testing work. Any help on how to do this would be much appreciated. Here's some code illustraiting what I'm trying to do:

public class Main {
    private SimpleObject simpleObject;

    public Main(SimpleObject o){
        this.simpleObject = o;
    }

    public int iDontWork(){
        return simpleObject.myList.size();
    }

    public int iWork(){
        return simpleObject.getMyList().size();
    }
}

My test:

@RunWith(JMock.class)
public class MainTest {
    Mockery context = new Mockery() {{
        setImposteriser(ClassImposteriser.INSTANCE);
    }};
    @Mock
    SimpleObject simpleObject;
    private Main main;

    @Before
    public void setup(){
        main = new Main(simpleObject);
    }

    @Test
    public void itWorks() {
        context.checking(new Expectations() {{
            oneOf(simpleObject).getMyList(); 
            will(returnValue(new ArrayList<String>(Arrays.asList("Hey"))));
        }});
        int i = main.iWork();
        assertEquals(1, i);
    }

    @Test
    public void itDoesntWork() {
        context.checking(new Expectations() {{
            oneOf(simpleObject).myList.size(); will(returnValue(1));
        }});
        int i = main.iDontWork();
        assertEquals(1, i);
    }
}

SimpleObject:

public class SimpleObject {
    public final List<String> myList;

    public SimpleObject(){
        myList = Collections.unmodifiableList(Arrays.asList("Hey"));
    }

    public List<String> getMyList(){
        return myList;
    }
}

A mock object implements methods of the real object. It does not have fields of the real object (even if these fields are public).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM