我从learnyouahaskell的书中获得了阅读器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
上行.hs
get :: String -> String -> IO B.ByteString
get token endpoint = do
req <- parseRequest endpoint
resp <- httpLBS $ withAuth token req
return $ getResponseBody resp
如何模拟httpLBS-调用与阅读器monad的集成测试?
编辑:
我现在几乎已经和读者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数据类型中定义该函数及其约束?
我保证,当最后一个问题被解决后,我会发布我的解决方案
在Haskell中,依赖注入只是更高阶的编程+currying。您可以按照以下方式编写代码。
-- where (? -> ?) is the type of httpLBS
get_ :: (? -> ?) -> String -> String -> IO B.ByteString
get_ httpFunc token endpoint = do
req <- parseRequest endpoint
resp <- httpFunc $ withAuth token req
return $ getResponseBody resp
getProduction = get_ httpLBS
getTest = get_ httpMock