我目前正在开发一个带有spring boot kotlin的网站,我正在尝试以xml格式阅读Google Trends Rss提要并将它们解析为Json。
我想添加单元测试来测试我的 Controller ,但我不知道究竟要测试什么。
这是我的数据类:
data class Rss (
val title: String,
val source: String,
val image: String,
val description: String,
val url: String
)
这是我的休息 Controller
@RestController
@RequestMapping(value="/rss")
class RssRestService {
@GetMapping(value = "/list/item")
@CrossOrigin("http://localhost:3000")
fun rss(): List<Rss>? {
val url = "https://trends.google.fr/trends/hottrends/atom/feed?pn=p1"
val reader = XmlReader(URL(url))
val feed: SyndFeed = SyndFeedInput().build(reader)
return feed.entries.subList(1,6)
.map { entry -> Rss(
title = entry.title,
image = entry.foreignMarkup[1].content[0].value.substring(2),
source = entry.foreignMarkup[2].content[0].value,
description = entry.foreignMarkup[3].content[1].value.toString(),
url = entry.foreignMarkup[3].content[1].value
) }
}
到目前为止我所做的测试是
@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DemoApplicationTests {
@Autowired
lateinit var testRestTemplate: TestRestTemplate
@Test
fun contextLoads() {
}
@Test
fun rssTest() {
val result = testRestTemplate.getForEntity("/rss/list/item", String::class.java)
Assert.assertNotNull(result)
Assert.assertEquals(HttpStatus.OK, result.statusCode)
}
我的问题是:我应该测试什么?以及如何测试输出是否写入?
最佳答案
您已经很难对 Controller 进行单元测试,因为它依赖外部 URL 来检索新闻提要的详细信息。
我会将与外部 URL 的交互提取到单独的服务,然后将此服务自动连接到您的 Controller 中。这将允许 yopu 在 Controller 的单元测试中使用此服务的 Mock 实现,然后您可以注入(inject)已知的提要项目并确保来自 Controller 的响应是正确的。
关于unit-testing - 使用 spring boot、kotlin 和 junit 进行 Rest Controller 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50210971/