參考文章
正文
引入maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
編寫測試代碼,詳細代碼如下:
import xx.SmsClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by hua on 2016/6/29.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = VaccineFrontStartUp.class)// 指定spring-boot的啓動類
@ActiveProfiles("de")
public class SMSClientTest {
private static final Logger logger = LoggerFactory.getLogger("TestSMS");
@Autowired
private SmsClient smsClient;
@Test
public void testSendSms() {
logger.info(String.format("smsClient:%s", smsClient));
String sendResult = smsClient.sendSMS("15600000001", "2016.06.29");
logger.info(String.format("發送結果爲:%s", sendResult));
}
}
總結
可以看到,對spring-boot項目進行單元測試是件容易的事兒,需要添加spring-boot-starter-test
依賴,然後
使用@RunWith
和@SpringApplicationConfiguration
註解,然後引入自己要測試的bean(在示例代碼中測試的是一個短信發送的bean),調用指定方法進行測試即可。
使用@ActiveProfiles(“de”)來指定活動的profile
技術越來越易用,要勇於嘗試