Home > OS >  can we use @Autowired without bean registration?
can we use @Autowired without bean registration?

Time:08-11

In the code below, surprisingly, when I use @AutoWired, the fields are set but this class has not been registered as a bean, and the program works correctly, but when I took the MockingTest bean from the context, it said that there is no such bean. Is it possible to use AutoWired without registering a class as a bean?

@SpringBootTest
public class MockingTest {
    @Autowired
    private ApplicationContext context;
    @Autowired
    private CollegeStudent collegeStudent;
    @Autowired
    private StudentGrades studentGrades;
    @Mock
    private ApplicationDao applicationDao;
    @InjectMocks
    private ApplicationService applicationService;

@BeforeEach
void setUp() {
    collegeStudent.setFirstname("Al");
    collegeStudent.setLastname("Zam");
    collegeStudent.setEmailAddress("[email protected]");
    collegeStudent.setStudentGrades(studentGrades);
}


@Test
@DisplayName("mockito testing")
public void testMocking() {
    when(applicationDao.addGradeResultsForSingleClass(studentGrades.getMathGradeResults()))
            .thenReturn(100.0);
    assertEquals(100.0, applicationService.addGradeResultsForSingleClass(studentGrades.getMathGradeResults()));
    verify(applicationDao).addGradeResultsForSingleClass(studentGrades.getMathGradeResults());
    verify(applicationDao,times(1)).addGradeResultsForSingleClass(studentGrades.getMathGradeResults());
}

}

CodePudding user response:

@SpringBootTest sets up multiple hooks into the test runner. One of them is to inject beans into @Autowired fields, without the test class itself being a bean.

@SpringBootTest actually does a lot of "magic" behind the scenes, just so that things just work like we might expect, without us thinking about them too much.

  • Related