当我测试 Spring 启动服务时,我不知道如何注入 @Autowired bean。我的 bean(Spring 从 application.yml 填充 @Value):@Componentpublic class NavigatorProperties { @Value("${timerDelay}") private String timerDelay; public String getTimerDelay() { return timerDelay; } public void setTimerDelay(String timerDelay) { this.timerDelay = timerDelay; }}我的api:public class ListenerApi implements IRestListenerApi { @Autowired private NavigatorProperties np; public String doSomething (...) { // This is my service method. // Here np.getTimerDelay() will return application.yml value. int timerDelay = Integer.decode(np.getTimerDelay()); ... }}这工作正常并且 int 值是正确的。这是我的测试:@RunWith(SpringRunner.class)@SpringBootTest(classes = {ListenerApiTest.class, NavigatorProperties.class})@FixMethodOrder(MethodSorters.NAME_ASCENDING)public class ListenerApiTest { @Autowired private NavigatorProperties np; // Can be autowired or a new Object. // Object to test. private ListenerApi listenerApi; @Test public void test01ForceNumberFormatException() { np.setTimerDelay("NumberFormatException"); // Inyect into ListenerApi } @Test public void test02ForceNullPointerException() { np.setTimerDelay(null); // Inyect into ListenerApi }在此测试评论中,我如何通过 @Autowired 输入 ListenerApi?
添加回答
举报
0/150
提交
取消