CodeThisAndThat
CodeThisAndThat

Reputation: 25

Test case utilizing Mockito is not returning expected String value

I have my set-up here @Before for my test case

r = RentACat.createInstance();
c1 = Mockito.mock(Cat.class);
        Mockito.when(c1.getId()).thenReturn(1);
        Mockito.when(c1.getName()).thenReturn("Jennyanydots");

c2 = Mockito.mock(Cat.class);
        Mockito.when(c2.getId()).thenReturn(2);
        Mockito.when(c2.getName()).thenReturn("Old Deuteronomy");

With my test case as

r.addCat(c1);
        r.addCat(c2);
        r.addCat(c3);
        
        //Execution Steps
        String ret = r.listCats();
        
        //Postconditions
        assertEquals("Return string is not equal to expected string with added cats", "ID 1. Jennyanydots\nID 2. Old Deuteronomy\", ret);

And this is my implementation of listCats();

    public String listCats() {
        // TODO
        StringBuilder retBuild = new StringBuilder();
        for(Cat c : cats) {
            if(c.getRented() == false) {
                retBuild.append(c.toString());
                retBuild.append("\n");
            }
        }
        return retBuild.toString();
    }

However, when I run this test case I am getting a return value of an empty string. I have tried some things like changing my implementation listCats(); such that

    public String listCats() {
        // TODO
        StringBuilder retBuild = new StringBuilder();
        for(Cat c : cats) {
            if(c.getRented() == false) {
                retBuild.append(c.toString());
                retBuild.append("\n");
                return retBuild.toString();

            }
        }
        return retBuild.toString();
    }

However, when I run this I am only getting one of the cats as had expected with the observed values as "Mock for Cat, hashCode: 10523xyz"

What am I doing wrong within my listCats() method?

Upvotes: 1

Views: 501

Answers (1)

0xh3xa
0xh3xa

Reputation: 4857

Yes, because you need to define the toString() behavior also in the mocked object. The string you have seen it's the default toString version for the mocked object. you can define yours like below.

Mockit.when(c1.toString()).thenReturn("Jennyanydots");
Mockit.when(c2.toString()).thenReturn("Old Deuteronomy");

Notice: if the Cat class is just POJO object with getter/setter no need to mock it you just fill with whatever you want from the data

Upvotes: 2

Related Questions