Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit for a method with while loop

Tags:

mockito

I am facing some difficulty in writing a JUnit test for a method with a While loop. My method looks like below:

private void deleteMethod(DeleteRequest dr){

    // below statement am calling some service which returns me a object after querying it from Database.
    SomeObject ob = db.getdata(dr);

    while(ob != null) {
        // this method deletes the Data from DB 
        db.deleteData(ob);
        // again calling the same service operation as we did before while loop. I have a situation where my service only returns single record at a time. It is avoidable that I need to do a dirty job.
        ob = db.getdata(dr);
    }

Below is my JUnit:

@Test
public void testDeleteMethod() throws Exception{
    DeleteRequest mockDR = new DeleteRequest();
    mockDR.setX(y);
    SomeObject mockOB = new SomeObject();
    mockOB.setZ(k);
    // making a mockcall to the method before I can assert anything
    mockClassObject.deleteMethod(mockDR); 
}

The above JUnit method is getting struck in execution for ever and I understand that its not getting out of the while loop. How I can approach this issue. Just to mention am using Mockito framework and am not aware if at all there is any way to handle this situation in Mockito.

like image 256
Abhiram Avatar asked Oct 27 '25 14:10

Abhiram


1 Answers

Using Mockito, you have to mock the db connection and inject it into your service using @InjectMocks, constructor injection, or via a setter before you test your method. This is how I would write your test.

@Test
public void testDeleteMethod() throws Exception{
    DeleteRequest deleteRequest = new DeleteRequest();
    deleteRequest.setX(y);
    SomeObject someObject = new SomeObject();
    someObject.setZ(k);

    Database db = Mockito.mock(Database.class);
    // Notice chain of calls
    Mockito.when(db.getdata(deleteRequest))
        .thenReturn(someObject).thenReturn(null);

    // TODO Inject the Database object into your mockClassObject.

    // making a mock call to the method before I can assert anything
    mockClassObject.deleteMethod(deleteRequest);

    Mockito.verify(db, Mockito.times(2)).getdata(deleteRequest);
    Mockito.verify(db).deleteData(someObject);
}

You can see that I chain the calls on the db.getData() method two times, the first time returns someObject and the second time returns null.

like image 56
Craig Avatar answered Oct 30 '25 13:10

Craig