我在我的项目中使用hazelcast并且我想要对一些函数进行单元测试,但我不希望它连接到真正的hazelcast并对其执行测试,因为我创建了一个自定义模拟类,它只使用scala map,因为在hazelcast中地图也在那里 这是我的代码
trait UserRepository {
def getUserObj(id: String):Option[User]
def addToUserRepo(user: User)
}
class UserRepo extends UserRepository{
def getUserObj(id: String):Option[User] = {
val userMap = hcastClient.getMap[String, User]("UserMap")
val userObj = userMap.get(id)
Option(userObj)
}
def addToUserRepo(user: User) = {
val directUserMap: IMap[String, User] = hcastClient.getMap[String,User]("UserMap")
directUserMap.set(user.uuid, user)
}
在这里我创建了一个简单的自定义模拟版本类,其功能相同;用scala map替换它:
class UserRepoMock extends UserRepository {
val map:Map[String,User]=Map[String,User]()
def getUserMap:Map[String,User] = {
map
}
def getUserObj(id: String):User = {
val userMap = getUserMap
val userObj = userMap.get(id)
userObj
}
def addToUserRepo(user: User) = {
val userMap = getUserMap
userMap.put(user.uuid, user)
}
class UserUtil(userRepo:UserRepo) {
def addUser(user:User):Boolean={
try{
userRepo.addToUserRepo(user)
true
}
catch {
case e:Exception=>false
}
def getUser(id:String):User={
val user=userRepo.getUserObj(id)
user
}
如果我希望将addUser
类的测试方法getUser
和UserUtil
单元化
通过这样做:
class UserUtilTest extends funSpec {
val userUtil=new UserUtil(new UserRepoMock)
userUtil.addUser //perform unit test on it
userUtil.getUser //perform unit test on it
// instead of doing this val userUtil=new UserUtil(new UserRepo)
}
但编译器不允许我这样做,有一些我不知道的东西,请帮助我如何实现所需的功能
这是编译器错误:
type mismatch; found : testhcastrepo.UserRepoMock required: com.repositories.UserRepo