Mongodb Kotlin跨junit测试共享伴生对象
我有一个集成测试,在这里我启动一个嵌入式MongoDB作为一个伴生对象。我想重用这段代码,但我不确定继承是否可行(如果可能) 它是一个Spring引导应用程序: 这是我的测试:Mongodb Kotlin跨junit测试共享伴生对象,mongodb,spring-boot,testing,kotlin,junit4,Mongodb,Spring Boot,Testing,Kotlin,Junit4,我有一个集成测试,在这里我启动一个嵌入式MongoDB作为一个伴生对象。我想重用这段代码,但我不确定继承是否可行(如果可能) 它是一个Spring引导应用程序: 这是我的测试: @RunWith(SpringRunner::class) @SpringBootTest class RequestRepositoryTest { @Autowired lateinit var requestRepository: RequestRepository companion object {
@RunWith(SpringRunner::class)
@SpringBootTest
class RequestRepositoryTest {
@Autowired lateinit var requestRepository: RequestRepository
companion object {
private val starter = MongodStarter.getDefaultInstance()
private var _mongod: MongodProcess? = null
private var _mongo: MongoClient? = null
@BeforeClass
@JvmStatic fun beforeTest(){
val port = 27017
val _mongodExe = starter.prepare(MongodConfigBuilder()
.version(Version.Main.DEVELOPMENT)
.net(Net("localhost", port, Network.localhostIsIPv6()))
.build())
_mongod = _mongodExe.start()
_mongo = MongoClient("localhost", port)
}
@AfterClass
@JvmStatic fun afterTest(){
_mongod?.stop()
}
}
@Test
fun store() {
val id = requestRepository.store(Request(requestId = "123"))
assertNotNull(id)
}
}
我的存储库类:
@Repository
class RequestRepository @Autowired constructor(val datastore: Datastore)
{
fun store(request : Request) : String =
datastore.save(request).id.toString()
}
所以我的问题是,在科特林,哪种方式才是正确的
更新编辑:作为一个外部对象,测试现在看起来更干净,JUnit外部资源在测试类之间完全可重用:
谢谢@Lovis
@RunWith(SpringRunner::class)
@SpringBootTest
class RequestRepositoryTest {
companion object {
@ClassRule
@JvmField
val mongoServer = MongoServer
}
@Autowired lateinit var requestRepository: RequestRepository
@Test
fun store() {
val id = requestRepository.store(Request(requestId = "123"))
assertNotNull( id )
assertTrue { ObjectId.isValid(id) }
}
}您应该能够使用jUnit的
@ClassRule
和外部资源
实现您想要的。不需要Kotlin魔法:-)
在单独的文件中定义对象
:
object MongoServer : ExternalResource() {
@Throws(Throwable::class)
override fun before() {
// before class
}
override fun after() {
// after class
}
}
然后在每次测试中使用它:
companion object {
@ClassRule
@JvmField
val mongoServer = MongoServer
}
ClassRule
注释在这里起作用,companion对象
是使其静态的必要条件,而@JvmField
注释是使字段公开的必要条件。这些都是jUnit规则系统的限制。您希望如何“重用”它?在另一个测试班?或者你的意思是为了类内的不同测试?@Lovis-在不同的测试类中。看起来很漂亮整洁。当我有时间尝试时,我会接受答案。谢谢它就像一个符咒,代码变得清晰易读!标记为被接受的答案。干杯