![](/img/trans.png)
[英]Can we change the autowired of a parent bean in a child constructor javaspring?
[英]can we use @Autowired without bean registration?
在下面的代碼中,令人驚訝的是,當我使用@AutoWired 時,設置了字段,但是這個 class 沒有注冊為 bean,程序正常工作,但是當我從上下文中取出 MockingTest bean 時,它說有沒有這樣的豆子。 是否可以在不將 class 注冊為 bean 的情況下使用 AutoWired?
@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("555@gmail.com");
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());
}
}
@SpringBootTest
在測試運行器中設置了多個掛鈎。 其中之一是將bean注入@Autowired
字段,而測試class本身就是一個bean。
@SpringBootTest
實際上在幕后做了很多“魔術”,只是為了讓事情像我們預期的那樣工作,而不需要我們過多地考慮它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.