![](/img/trans.png)
[英]Spring-boot: JUnit test ApplicationContext failed to load
[英]spring-boot junit load test property resource for unit test
我正在使用spring-boot-1.5 。 在單元測試期間,有什么方法可以在src / test / resources中加載application.properties嗎? 我知道如何使用集成測試加載它,我們可以使用@SpringBootTest或@ContextConfiguration,但是我想在單元測試期間使用application.properties。
讓我解釋一下我的情況,
@SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class })
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class BookBackendApplication {
public static void main(String[] args) {
SpringApplication.run(BookBackendApplication.class, args);
}
}
@Service
public class BookService {
@Value("${book-list:ACTIVE}")
private List<String> bookList = new ArrayList<>();
@Value("${book-status:PURCHASING}")
private String bookStatus;
public BookResponse purchaseBook(BookRequest bookRequest) {
if(bookRequest.getStatus().equals(bookStatus)) { //Here getting NPE while executing unit test
....
}
}
}
單元測試
@RunWith(SpringRunner.class)
public class BookServiceTest {
@InjectMocks
private BookService bookService;
@Test
public void testBookActivate() throws IOException {
BookResponse bookResponse = bookService.purchaseBook(bookRequest);
...
}
}
在運行此單元測試時,屬性未加載,因此在BookService.java中獲得了NPE。 運行單元測試時,有什么方法可以加載src / test / resource / application.properties嗎?
任何指針或幫助將是非常可觀的。
您可以使用@TestPropertySource
參見本頁: 覆蓋默認測試中的默認彈簧啟動應用程序屬性設置
最后,我得到了答案。 我使用下面的代碼在運行模擬時設置靜態字段。 ReflectionTestUtils解決了該問題。
@RunWith(SpringRunner.class)
public class BookServiceTest {
@InjectMocks
private BookService bookService;
@Before
public void setup() {
ReflectionTestUtils.setField(bookService, "bookStatus", "PURCHASING");
ReflectionTestUtils.setField(bookService, "bookList", Arrays.asList("ACTIVE","ACTIVATING"));
}
@Test
public void testBookActivate() throws IOException {
BookResponse bookResponse = bookService.purchaseBook(bookRequest);
...
}
}
非常感謝您的支持。 讓我們繼續幫助別人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.