2

I have an repository method that returns List, which under the hood uses CriteriaQueryTupleTransformer.TupleImpl. In tests I want to mock Repository and on Repository.method return predefined mocked data.

Something like this:

MyRepository myRepository = mock(MyRepository.class);
List<Tuple> = new ArrayList<>();
Tuple tuple = TupleImpl.Builder() //TupleImpl is private class and has no Factory or Builders
            //.addMockedData()
            //.addMockedData()
            .build();

tuples.add(tuple);
//add more mocked data

when(myRepository.findByIds(any())).thenReturn(tuples);

//Assert business logic that everything 
//went as expected when a specific Tuple structure was returned by repo

My main problem here is that I need to instantiate CriteriaQueryTupleTransformer.TupleImpl which is any private class, and I couldn't find any Builders or Factory methods for easy creation.

3
  • 1
    Why don't you mock the Tuple interface then? Feb 8, 2019 at 14:20
  • This is what i did in the end, don't know why it didn't occur to me in the first place. Thx for help! Feb 11, 2019 at 7:48
  • @LukaŠpoljarić it would be useful for others (like me) to see how you did it. Besides, I would upvote the question and answer. Sep 8, 2023 at 7:10

1 Answer 1

1

I did what you said in a comment. Answering here so people see what the solution looks like. Using Mockito.

    private Tuple mockedTuple;
    private List<Tuple> tupleList;

    @Before
    public void setUp() {
        mockedTuple = mock(Tuple.class);

        tupleList = new ArrayList<>();
        tupleList.add(mockedTuple);
    }

    @Test
    public void testTuple() {
        when(mockedTuple.get(anyInt())).thenReturn(1);
        when(repository.something(any())).thenReturn(tupleList);
        
        // assertions
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.