简体   繁体   中英

How to test a service that get data from a database using JUnit and Mockito

i write a java service that get a data from database :

public List<Operation> listOperations(String code){

//some business logic...

}

i tested the service manually with the a code from my database listOperations("CEA1"); and it works fine and it return to me a List with 3 Operation Objects(the same result in my database).

now i want to test my service using Mockito and JUnit but i'm beginner in unit testing (but i know what is the concepts of unit testing,mocking...),

this is my uncompleted test class :

@RunWith(MockitoJUnitRunner.class)
public class MyserviceTest {

    @Mock
    private OperationRepository  operationRepositoryMock;


    @InjectMocks
    private BanqueServiceImpl banqueServiceImpl;

    @Before
    public void setup() {
      MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testListOfOperation(){

        String code = "CEA1";

        //to check if my service is working good ,the code 'CEA1' should return a list with 3 Operation object
        when(operationRepositoryMock.listOperations(code)). // i dont know how to mock the result


boolean result = banqueServiceImpl.listOperations(code); // i don't know how to assert that the service return a list that contains 3 Operation object

        //assertTrue(result);
    }

please can anyone help me to complete my test code , note i'm working in a spring boot project.

Regards!

First prepare your list of Operation

Operation sampleOperation = new Operation();
List<Operation> operationList = new ArrayList<Operation>();
operationList.add(sampleOperation);

now use mockito to return operationList when listOperations() method is called

when(operationRepositoryMock.listOperations(eq("CEA1"))).thenReturn(operationList);

Now you can use assertion to verify size of list or verify content of list

assertThat("size is equal to 1", banqueServiceImpl.listOperations(code).size(), is(1));

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