我想测试以下函数:
def curl(host: String, attempt: Int = 200): ZIO[Loggings with Clock, Throwable, Unit]如果环境只使用标准的ZIO环境,如Console with Clock,测试将开箱即用:
testM("curl on valid URL") {
(for {
r <- composer.curl("https://google.com")
} yield
assert(r, isUnit))
}测试环境将由zio-test提供。
所以问题是,如何用我的Loggings模块扩展TestEnvironment?
发布于 2020-02-04 03:18:17
请注意,此答案适用于RC17,并将在RC18中发生重大变化。你说得对,就像在组合环境的其他情况下一样,我们需要实现一个函数来从我们拥有的模块构建我们的整个环境。Spec有几个内置的组合子,比如provideManaged来做这件事,所以你不需要在你的测试中去做。所有这些都具有“普通”变体和“共享”变体,前者将为套件中的每个测试提供单独的环境副本,后者将在创建成本高昂的资源时为整个套件创建一个环境副本,如Kafka服务。
您可以在下面看到一个使用provideSomeManaged来提供将测试环境扩展到测试的环境的示例。
在RC18中,将有许多其他提供的变体,等同于ZIO上的那些变体,以及一个新的层概念,使为ZIO应用程序构建组合环境变得更加容易。
import zio._
import zio.clock._
import zio.test._
import zio.test.environment._
import ExampleSpecUtil._
object ExampleSpec
extends DefaultRunnableSpec(
suite("ExampleSpec")(
testM("My Test") {
for {
time <- clock.nanoTime
_ <- Logging.logLine(
s"The TestClock says the current time is $time"
)
} yield assertCompletes
}
).provideSomeManaged(testClockWithLogging)
)
object ExampleSpecUtil {
trait Logging {
def logging: Logging.Service
}
object Logging {
trait Service {
def logLine(line: String): UIO[Unit]
}
object Live extends Logging {
val logging: Logging.Service =
new Logging.Service {
def logLine(line: String): UIO[Unit] =
UIO(println(line))
}
}
def logLine(line: String): URIO[Logging, Unit] =
URIO.accessM(_.logging.logLine(line))
}
val testClockWithLogging
: ZManaged[TestEnvironment, Nothing, TestClock with Logging] =
ZIO
.access[TestEnvironment] { testEnvironment =>
new TestClock with Logging {
val clock = testEnvironment.clock
val logging = Logging.Live.logging
val scheduler = testEnvironment.scheduler
}
}
.toManaged_
}发布于 2020-02-04 02:35:49
这就是我的想法:
testM("curl on valid URL") {
(for {
r <- composer.curl("https://google.com")
} yield
assert(r, isUnit))
.provideSome[TestEnvironment](env => new Loggings.ConsoleLogger
with TestClock {
override val clock: TestClock.Service[Any] = env.clock
override val scheduler: TestClock.Service[Any] = env.scheduler
override val console: TestLogger.Service[Any] = MyLogger()
})
}使用带有provideSome的TestEnvironment来设置我的环境。
https://stackoverflow.com/questions/60045180
复制相似问题