Expand my Community achievements bar.

How to write junit for the below code

Avatar

Level 4

wfsession.complete(workItem, (wfsession.getRoutes(workItem,false)).get(0));

wfsession.suspendWorkflow(workItem.getWorkflow());

2 Replies

Avatar

Level 4

Try this

 

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

class WorkflowSessionTest {

private WorkflowSession wfsession;
private WorkItem workItem;
private Route route;

@BeforeEach
void setUp() {
// Mocking the WorkflowSession and WorkItem
wfsession = mock(WorkflowSession.class);
workItem = mock(WorkItem.class);
route = mock(Route.class);

// Mocking getRoutes to return a list with one route when false is passed
when(wfsession.getRoutes(workItem, false)).thenReturn(List.of(route));
}

@test
void testCompleteAndSuspendWorkflow() {
// Act - call complete on the work item
wfsession.complete(workItem, wfsession.getRoutes(workItem, false).get(0));

// Verify complete is called with the correct route
verify(wfsession).complete(workItem, route);

// Act - suspend the workflow associated with the work item
wfsession.suspendWorkflow(workItem.getWorkflow());

// Verify suspendWorkflow is called with the correct workflow
verify(wfsession).suspendWorkflow(workItem.getWorkflow());
}
}

Avatar

Level 3

Hi @djohn98390536 
Please try this

import static org.aem.core.wked.*;

import com.example.workflow.WorkflowSession;
import com.example.workflow.WorkItem;
import com.example.workflow.Route;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Collections;
import java.util.List;

public class WorkflowManagerTest {

    @Mock
    private WorkflowSession wfSession;

    @Mock
    private WorkItem workItem;

    @Mock
    private Route route;

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void testCompleteWorkItem() {
        // Arrange
        List<Route> routes = Collections.singletonList(route);
        when(wfSession.getRoutes(workItem, false)).thenReturn(routes);

        // Act
        wfSession.complete(workItem, wfSession.getRoutes(workItem, false).get(0));

        // Assert
        verify(wfSession).complete(workItem, route);
    }

    @Test
    public void testSuspendWorkflow() {
        // Arrange
        when(workItem.getWorkflow()).thenReturn("workflowId");

        // Act
        wfSession.suspendWorkflow(workItem.getWorkflow());

        // Assert
        verify(wfSession).suspendWorkflow("workflowId");
    }
}