0

My problem is extremely simple but spring is making hell of my life to solve it.

I have an entity (Board) which has a collection (Column) that is LAZY (and please don't suggest to make it eager)

In my test class I want to create a simple test case where I can assert that the Columns are being created into the Board

@Test
   void testAddColumn() {
      Board board = new Board("title", groupId);
      board = boardRepository.save(board);

      assertTrue(board.getColumns().isEmpty());

      Column column = new Column(board, "column title", 2);
      column = boardService.addColumn(board.getId(), column);

     
      assertEquals(1, boardRepository.findById(board.getId()).get().getColumns().size()); //this line breaks

      Column column2 = new Column(board, "column title2", 1);
      boardService.addColumn(board.getId(), column2);
      assertEquals(2, boardRepository.findById(board.getId()).get().getColumns().size());

      boardService.delete(board.getId());
      
   }

But as you can imagine I get: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role could not initialize proxy - no Session

I've tried to:

@Autowired
   private SessionFactory sessionFactory;

then

 SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
      sessionFactory.openSession();

but yet hibernate cant find session and throw same error.

I've added @Transactional to the test method, them the connection works, but the whole test logic fails because hibernate wont load intermediary states, and everytime i try to findById() it wont refresh

How can i solve this problem, manually open connections and fetch this lazy entities just for this test class without making everything eager

Rafael Lima
  • 3,079
  • 3
  • 41
  • 105
  • Did you try/check similar questions like https://stackoverflow.com/questions/19813492/getting-lazyinitializationexception-on-junit-test-case ? – Ale Zalazar Jun 30 '22 at 20:45
  • Inject the `EntityManager` and before a `findById` call `flush` and `clear` (and add `@Transactional` to the test). If you don't you won't get intermediate steps persisted/flushed to the database and the `findById` will only return the value from the 1st level cache. However the fact that it doesn't simply work is more of an indication that the way you are adding columns to the board is wrong and you probably should fix the actual service method instead of doing what you do now. – M. Deinum Jul 01 '22 at 07:22

0 Answers0