SpringBoot项目编写测试用例,在测试类中使用@Autowired注解拿到bean的值为null。
public class OrderBookServiceTest {
@Autowired
private OrderBookService orderBookService; //null
@Test
@Transactional
public void testHandleJson(){
String msg="{\"asks\":[[0.51,14220.0],[0.52,20000.0]],\"bids\":[[0.4981,174.2],[0.498,15387.036],[0.497,20000.0],[0.4967,12.0],[0.3,2000.0]],\"e\":\"AABUSDT@delta_book.50\",\"t\":1600077555484}";
JSONObject jsonObject = JSON.parseObject(msg);
orderBookService.handleJsonObject(jsonObject);
OrderBookView orderBookView = orderBookService.getOrderBookView("AABUSDT");
assertThat(orderBookView).isNotNull();
List<BookEntry> askSnapShot = orderBookView.getAskSnapShot();
assertThat(askSnapShot.size()).isEqualTo(2);
assertThat(orderBookView.getBidsSnapShot().size()).isEqualTo(5);
}
}
网上查阅找发现说是要加上以下注解即可
@SpringBootTest
@RunWith(SpringRunner.class)
@SpringBootTest
@RunWith(SpringRunner.class)
public class OrderBookServiceTest {
@Autowired
private OrderBookService orderBookService; //null
@Test
@Transactional
public void testHandleJson(){
String msg="{\"asks\":[[0.51,14220.0],[0.52,20000.0]],\"bids\":[[0.4981,174.2],[0.498,15387.036],[0.497,20000.0],[0.4967,12.0],[0.3,2000.0]],\"e\":\"AABUSDT@delta_book.50\",\"t\":1600077555484}";
JSONObject jsonObject = JSON.parseObject(msg);
orderBookService.handleJsonObject(jsonObject);
OrderBookView orderBookView = orderBookService.getOrderBookView("AABUSDT");
assertThat(orderBookView).isNotNull();
List<BookEntry> askSnapShot = orderBookView.getAskSnapShot();
assertThat(askSnapShot.size()).isEqualTo(2);
assertThat(orderBookView.getBidsSnapShot().size()).isEqualTo(5);
}
}
加上后发现还是报错。需要将注入的类加载@SpringBootTest注解的class属性上
@SpringBootTest(classes = {OrderBookServiceImpl.class, AlgoServiceImpl.class})
@RunWith(SpringRunner.class)
public class OrderBookServiceTest {
@Autowired
private OrderBookService orderBookService;
@Autowired
private AlgoService algoService;
@Test
@Transactional
public void testHandleJson(){
String msg="{\"asks\":[[0.51,14220.0],[0.52,20000.0]],\"bids\":[[0.4981,174.2],[0.498,15387.036],[0.497,20000.0],[0.4967,12.0],[0.3,2000.0]],\"e\":\"AABUSDT@delta_book.50\",\"t\":1600077555484}";
JSONObject jsonObject = JSON.parseObject(msg);
orderBookService.handleJsonObject(jsonObject);
OrderBookView orderBookView = orderBookService.getOrderBookView("AABUSDT");
assertThat(orderBookView).isNotNull();
List<BookEntry> askSnapShot = orderBookView.getAskSnapShot();
assertThat(askSnapShot.size()).isEqualTo(2);
assertThat(orderBookView.getBidsSnapShot().size()).isEqualTo(5);
}
为什么是这样的呢。我的项目里面包含多个子工程,子工程里面没有Application.java启动类。
@SpringBootTest次注解的作用就是启动Spring 容器。没有这个注解的测试类在运行的时候并没有启动Spring容器,容器没有启动,那又怎么能通过@Autowired注解来注入呢