Announcement Announcement Module
Collapse
No announcement yet.
Problem with ReflectionTestUtils on transactional components Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Problem with ReflectionTestUtils on transactional components

    Hi,

    I have the following Spring component with an autowired field.

    Code:
    @Service
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Throwable.class)
    public class PlageCalculServiceImpl implements PlageCalculService {
    
       @Autowired
       private ParametresStore parametresStore;
    
       @Override
       public PlageHoraire getPlagePreparation(Date lundi) {...}
    
    }
    I wrote the followowing unit test, using ReflectionTestUtils to inject the parametresStore autowired field :

    Code:
    @RunWith(SpringJUnit4ClassRunner.class)
    @Transactional
    @ContextConfiguration(locations = {
       "classpath:spring-test.xml",
       "classpath:spring-datasource-test.xml",
       "classpath:spring-hibernate-test.xml"})
    public class PlageCalculServiceTest {
    
       @Autowired
       private PlageCalculService plageCalculService;
    
       @Test
       public void testGetPlagePreparationDimanche() {
          ...
          ParametresStore mock = new ParametresStoreMock();
          ReflectionTestUtils.setField(this.plageCalculService, "parametresStore", mock, ParametresStore.class);
    		
          Calendar lundi = new GregorianCalendar(2010, Calendar.NOVEMBER, 8, 5, 0);
          PlageHoraire plagePreparation = this.plageCalculService.getPlagePreparation(lundi.getTime());
          ...
       }
    }
    When I run unit tests, I have the following stack trace :

    Code:
    java.lang.IllegalArgumentException: Could not find field [parametresStore] on target [xxx.PlageCalculServiceImpl@19478c7]
    	at org.springframework.test.util.ReflectionTestUtils.setField(ReflectionTestUtils.java:106)
    If I remove @Transactional annotation from my Spring component, everything works fine.

    I use Spring 3.0.4.

    Any idea how I could solve this problem ?

    Thanks in advance,

    Olivier

  • #2
    Proxy

    The problem is that @Transactional creates a proxy on your object which doesn't expose the private fields so the reflection utils can't find the field you're trying to set. I'm facing the same problem myself with AOP-AutoProxy. Did you find a solution to this?

    Comment


    • #3
      Did you try the three argument version of setField?

      Hi guys,

      Did you try the three argument version of setField method in ReflectionTestUtils? I got the same error using the four argument version, but switching to the three argument version solved it in my case.

      Cheers,

      Johan

      Comment

      Working...
      X