我想測驗一些 functinality,一個帶有自動裝配的 repo 的服務。我不想模擬自動裝配,這更像是一個用于除錯的集成測驗。
我的測驗如下
@SpringBootConfiguration
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ThrottleRateServiceTest {
ThrottleRateService service = null;
@BeforeEach
public void setUp() {
service = new ThrottleRateServiceImpl();
}
@Test
public void testThrottoling() {
service.isAllowed("test");
}
}
代碼非常簡單
@Service
public class ThrottleRateServiceImpl implements ThrottleRateService {
private final Logger logger = LogManager.getLogger(ThrottleRateServiceImpl.class);
@Autowired
ThrottleRateRepository throttleRateRepository;
問題是throttleRateRepository 始終為空。
我之前已經設法測驗過這種代碼。使用 Junit 4
@RunWith(SpringJUnit4ClassRunner.class)
它自動裝配了所有的豆子。自從我進行這種集成測驗以來已經有一段時間了,這一切都隨著 Junit 5 發生了變化。謝謝或任何幫助。
uj5u.com熱心網友回復:
該代碼中的問題:
@BeforeEach
public void setUp() {
service = new ThrottleRateServiceImpl();
}
您不應該手動創建 bean。在這種情況下,Spring 無法管理它并自動裝配存盤庫。
如果您需要在每次方法呼叫之前重新創建您的服務,您可以使用類注釋
@DirtiesContext(methodMode = MethodMode.AFTER_METHOD)。您可以在此處閱讀更多相關資訊。
取而代之的是,ThrottleRateServiceImpl像存盤庫一樣自動裝配。此外,為了正確的自動裝配,您可能需要進行測驗配置。它可以是內部靜態類,也可以是單獨的類。
@SpringBootConfiguration
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class ThrottleRateServiceTest {
@TestConfiguration
static class TestConfig {
@Bean
public ThrottleRateService throttleRateService() {
return new ThrottleRateServiceImpl();
}
}
@Autowired
ThrottleRateService service;
@Test
public void testThrottoling() {
service.isAllowed("test");
}
}
您可以在本教程中閱讀有關初始化 bean 以進行測驗和測驗配置的更多資訊。
此外,官方檔案非常有幫助:
如果您使用的是 JUnit 4,請不要忘記將 @RunWith(SpringRunner.class) 添加到您的測驗中,否則注釋將被忽略。如果您使用的是 JUnit 5,則無需添加等效的 @ExtendWith(SpringExtension.class) 作為 @SpringBootTest 并且其他 @… Test 注釋已經用它進行了注釋。
uj5u.com熱心網友回復:
已修復,我所做的是用 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 替換 @SpringBootTest
并自動裝配了 ThrottleRateService
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ThrottleRateServiceTest {
@Autowired
ThrottleRateService service;
@Test
public void testThrottoling() {
service.isAllowed("test");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/368439.html
上一篇:更新成功但未進行任何更改
