【发布时间】:2018-11-13 15:38:43
【问题描述】:
我从 learnyouahaskell 书中获得了 reader-monad 的基本功能,并且我在这里看到了一些建议,可以使用它进行依赖注入。 即使在stackoverflow上有一些示例,我也不知道如何使用它进行集成测试。
我的代码是:
list :: Ctx -> [String] -> IO String
list ctx args = do
d <- eitherDecode <$> Uplink.get (token ctx) (endpointActivities ctx) :: IO (Either String Activities)
case d of
Left err -> return err
Right result -> return $ unlines . filterByPrefix (parsePrefix args) . extractNames $ activities result
uplink.hs
get :: String -> String -> IO B.ByteString
get token endpoint = do
req <- parseRequest endpoint
resp <- httpLBS $ withAuth token req
return $ getResponseBody resp
如何模拟 httpLBS - 调用 reader-monad 的集成测试?
编辑:!!!!
我现在几乎已经有了 reader-monad。剩下的唯一问题是我不知道如何在我的 Ctx 数据类型中定义 httpsLBS 函数。
httpLBS-函数签名:
httpLBS :: MonadIO m => Request -> m (Response ByteString)
我的 Ctx 数据类型定义:
data Ctx =
Ctx {
token :: String,
endpointActivities :: String,
endpointTimeTrackingStart :: String,
httpLBSFunc :: MonadIO m => Request -> m (Response ByteString)
} deriving (Show)
我总是得到错误:不在范围内:类型变量'm' 如何在我的 Ctx-data-type 中定义该函数及其约束?
我保证,当最后一个问题解决后,我会发布我的解决方案
【问题讨论】:
-
我不确定我知道依赖注入到底是什么,但为什么不通过http客户端函数参数化
get,例如:get myHttpLBS token endpoint = do ...。Reader是围绕参数传递的抽象。我不倾向于使用它,除非:1)我已经有一个 monad 堆栈,2)我有多个相互调用的顶级函数,特别是我想传递一些值 通过一个函数,即有一些函数除了将参数传递给其他函数之外什么都不做。其他人可能会有不同的感觉 -
在函数式编程中,you can't use dependency injection because it makes everything impure。相反,您可以组合函数,尽可能多地保持它们的纯净。
-
你写的是
uplink.hs吗?不要硬编码httpLBS;使其成为参数。
标签: haskell dependency-injection