I have this problem where Mockito returns the result the actual controller would have given if the service has started. I want it to return the goats list I made and set in the when() function.
package com.goatpool.goatpool;
import com.goatpool.goatpool.controller.GoatController;
import com.goatpool.goatpool.model.Goat;
import com.goatpool.goatpool.service.HBMGoatService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RunWith(MockitoJUnitRunner.class)
class GoatControllerTest {
@InjectMocks
GoatController goatController;
@Mock
HBMGoatService hbmgoatService;
@Before
public void setup(){
//runs before the tests
}
@Test
void testGetAllGoats() throws Exception {
//Arrange
List<Goat> goats = new ArrayList<>();
goats.add(new Goat(1, "1","20001","buck", new Date() ,12.02f,1,3,24.68f,null,"Some Info",true,100));
goats.add(new Goat(2,"2","20056","doe",new Date() ,16.02f,1,3,20.68f,null ,"Some Info",true,12));
goats.add(new Goat(3,"3","21060","doe",new Date() ,16.02f,1,3,0f,null,"No Info",true,12));
goats.add(new Goat(4,"4","1212","buck",new Date() ,1.3f,1,3,0.5f,null,"No Info",true,12));
//Act
MockitoAnnotations.initMocks(this);
Mockito.when(hbmgoatService.getGoatList()).thenReturn(goats); //mock
List<Goat> result = goatController.getAllGoats();
//Assert
String actualResults = result.toString();
String expectedResults = goats.toString();
Assert.assertEquals(expectedResults, actualResults);
}
}