10BC0 CrudRepository MockBean not injected into Component being tested · Issue #6541 · spring-projects/spring-boot · GitHub
[go: up one dir, main page]

Skip to content

CrudRepository MockBean not injected into Component being tested #6541

@jtbeckha

Description

@jtbeckha

Testing this class

@Component
public class DemoComponent {

  @Autowired
  private DemoRepository demoRepository;

  public DemoEntity getByAttribute(String attribute) {
    return demoRepository.findFirstByAttribute(attribute);
  }
}

where DemoRepository is a Spring Data JPA style repository

@Repository
public interface DemoRepository extends CrudRepository<DemoEntity, Long> {

  DemoEntity findFirstByAttribute(String attribute);

}

This is the test

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoComponentTest {

  @MockBean
  private DemoRepository demoRepository;
  @Autowired
  private DemoComponent demoComponent;

  @Test
  public void testGetDemo_byAttribute() {
    String attribute = "test";
    when(demoRepository.findFirstByAttribute(attribute)).thenReturn(new DemoEntity(attribute));

    demoComponent.getByAttribute(attribute);
    assertNotNull(demoComponent.getByAttribute(attribute));
  }
}

The test fails, because the demoRepository mock isn't being injected into demoComponent during the test.

FWIW I figured out that if I remove the CrudRepository superclass from DemoRepository the test passes so it could be related to that

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0