Skip to content

@SpyBean does not work with generics #7625

@lincetto

Description

@lincetto

I'm trying to unit-testing a Spring batch job inside Spring boot using JUnit.
I wrote this test class where I want to spy the bean ItemReader:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
@ActiveProfiles({"dev", "batch", "test-jobs"})
public class BatchJobTest {

	@Autowired
	private JobLauncherTestUtils jobLauncherTestUtils;
    	
	@Autowired 
	@Qualifier("contactDownloadAckJob")
	private  Job contactDownloadAckTaskJob;

	@SpyBean
	private ItemReader<CrsOscContact> reader;

	@Test
	public void testJob() throws Exception {
		given(this.reader.read()).willReturn(new CrsOscContact());
		//... blah blah blah
	}	
}

When I run this test, it seems that the @SpyBean annotation does not do its job, that should be proxying the ItemReader bean that's already present in the context, and so I obtain the (correct) exception because, as per definition, if the bean is not found it tries to instantiate a new bean of that type (and I have specified an interface) :

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.item.ItemReader]: Specified class is an interface

I'm pretty sure that the bean (of ItemReader type) is already in the context because :

  • debugging, I see that the target bean instantiation is correctly processed
  • if I change the @SpyBean annotation to an @Autowired annotation, the instance of previous point is correctly injected

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions