우리는 스칼라 2.10.2를 사용하고 있으며, DAO에는 Slick 1.0.1을 사용하고 있습니다. 우리는 ScalaMock으로 DAO를 모의하려고합니다. 나는 조롱 된 DAO를 주입하는 좋은 방법을 찾아 내려하고 있습니다. 몇 년 동안 Java를 사용해 왔지만 2 주 전에 스칼라를 사용하기 시작했습니다.스칼라에 조롱 된 싱글 톤 객체를 삽입하려면 어떻게해야합니까?
(구문 오류를 무시하고, 나는 여전히 타입 시스템을 만족시키는 지 않고 코드를 응축 한)처럼 지금 우리의 코드는
abstract class RichTable[T](name: String)
extends slick.driver.MySQLDriver.simple.Table[T](name) {
type ItemType = T
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
...
}
object Users extends RichTable[User]("users") {
def crypted_password = column[String]("crypted_password")
...
}
case class User(id: Option[Int] = None, crypted_password: String) {
def updatePassword(...) = {
Users.where(_.id === id).map{e => e.crypted_password}.update("asdf")
}
}
의 DAO의 모든 RichTable[T]
에서 상속 싱글 개체 보인다
우리는 사용자와 다른 싱글 톤 DAO 객체를 모방 할 수 있기를 원합니다. 지금 모든 단위 테스트가 데이터베이스를 치고 있습니다. 그러나 우리가 다루는 문제는 모의 싱글 톤 객체를 주입하는 방법입니다. 우리가 지금까지 가지고 올 한 솔루션입니다 : 우리는 Users
에서 혼란의 과도한 양을 추가하지 않습니다 Users()
, 우리의 모든 참조를 변경하고
object DAORepo {
var usersDAO : Users.type = Users
var anotherDAO : Another.type = Another
...
}
object Users extends RichTable[User]("users") {
def apply() : Users.type = DAORepos.usersDAO
}
def updatePassword(...) = {
Users().where(_.id === id).map{e => e.crypted_password}.update("asdf")
}
def test = {
val mockUsers = mock[Users]
DAORepo.usersDAO = mockUsers
// run test using mock repo
}
. 그러나, DAORepo
에 vars를 사용하면 냄새가 좋지 않으며 누구나 개선 할 수있는 제안이 있는지 궁금합니다.
내가 Real-World Scala: Dependency Injection (DI) 및 Component Based Dependency Injection in Scala을 읽었습니다 - 나는 내가 DAORepo,
trait UsersRepo {
val usersDAO : Users.type = Users
}
trait DAORepo extends UsersRepo with AnotherRepo { }
trait UsersTestRepo {
val usersDAO : Users.type = mock[Users]
}
하지만 난 아직도 내가 새로운 특성을 주입하는 것 이해가 안 돼요 같은 것을 구성하는 특성을 사용하는 방법을 이해 생각한다. 나는 object DAOWrapper
에서 하나의 VAR과 object DAORepo
두 다스 바르를 대체
class DAORepoImpl extends DAORepo { }
object DAOWrapper {
var repo : DAORepo = new DAORepoImpl
}
def test = {
DAOWrapper.repo = new DAORepoImpl with UsersTestRepo
}
처럼 뭔가를 할 수 있지만, 거기에 어떤 바르없이이 작업을 수행하는 깨끗한 방법이 될한다고처럼 보인다.
감사하지만 전 자바 사용자 –
을에게 설명 주제에 좋은 자원의 부족이있다 Sebastien Lorber 감사합니다. Spring 예제는 큰 도움이되었습니다. –