How to instatiate CRUDRepository inside Junit

I am trying to make a Junit test for a spring project. There is a @Service class in project which has CRUDRepository objects as its member variables.
How do I get this object in My Junit context. Normally I can instantiate an Object but here there is no clear way of instantiating CRUDRepository Objects.
@ContextConfiguration(classes = ApplicationConfig.class)
public class WorkflowTemplateTest {

    private static final ObjectMapper mapper = new ObjectMapper();

    private WebApplicationContext webApplicationContext;

    private ApplicationConfig applicationConfig;

    private MockMvc mockMvc;

    public void setUp() throws Exception {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();

Open in new window

public class ApplicationConfig {
    public TemplateService getTemplateService() {
        return templateService;

    public ApplicationConfig setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
        return this;

    private TemplateService templateService;

Open in new window

public class TemplateService {

    private final WorkflowRepository workflowRepository;
    public TemplateService(
                           WorkflowRepository workflowRepository,
                          ) {
        this.workflowRepository = workflowRepository;


    public Workflow saveWorkflow(Workflow workflow) {

    public Workflow getWorkflow(Integer id) {
        return workflowRepository.getWorkflowById(id);

Open in new window

In the spring web application i think spring automatically initializes the workflowRepository but how will i do that when instantiating in the Junit.
What do i pass in the templateService constructor.

public interface WorkflowRepository extends CrudRepository<Workflow, Integer> {
    Workflow getWorkflowById(Integer id);

    List<Workflow> getWorkflowByWorkflowTemplate(WorkflowTemplate workflowTemplate);

    List<Workflow> getWorkflowByInitiatorOrderByCreatedOnDesc(WorkflowUser workflowUser);

Open in new window


Please help in getting me the Whole templateService Object.
Rohit BajajAsked:
Who is Participating?
Why don't you just mock the object you need? Then you can just test the business login without having to actually use the CRUD objects. These you can test in other test cases using an in-memory database.
This is a perfectly valid answer.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.