PageRenderTime 40ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/src/test/scala/DAOTest.scala

http://github.com/havocp/mongo-scala-thingy
Scala | 80 lines | 67 code | 13 blank | 0 comment | 0 complexity | 019d157642140cab28b8e34774cc429a MD5 | raw file
Possible License(s): Apache-2.0
  1. import com.mongodb.casbah.commons.MongoDBObject
  2. import com.mongodb.casbah.MongoCollection
  3. import com.ometer.bson.Implicits._
  4. import com.ometer.bson._
  5. import com.ometer.casbah._
  6. import org.bson.types._
  7. import org.junit.Assert._
  8. import org.junit._
  9. import play.test._
  10. package foo {
  11. case class Foo(_id : ObjectId, intField : Int, stringField : String)
  12. object Foo extends CasbahCollectionOperationsWithObjectId[Foo] {
  13. override protected lazy val collection : MongoCollection = {
  14. MongoUtil.collection("foo")
  15. }
  16. def customQuery[E : Manifest]() = {
  17. syncDAO[E].find(BObject("intField" -> 23))
  18. }
  19. }
  20. case class FooWithIntId(_id : Int, intField : Int, stringField : String)
  21. object FooWithIntId extends CasbahCollectionOperations[FooWithIntId, Int] {
  22. override protected lazy val collection : MongoCollection = {
  23. MongoUtil.collection("fooWithIntId")
  24. }
  25. def customQuery[E : Manifest]() = {
  26. syncDAO[E].find(BObject("intField" -> 23))
  27. }
  28. }
  29. }
  30. class DAOTest extends UnitTest {
  31. import foo._
  32. @org.junit.Before
  33. def setup() {
  34. MongoUtil.collection("foo").remove(MongoDBObject())
  35. MongoUtil.collection("fooWithIntId").remove(MongoDBObject())
  36. }
  37. @Test
  38. def testSaveAndFindOneCaseClass() {
  39. val foo = Foo(new ObjectId(), 23, "woohoo")
  40. Foo.caseClassSyncDAO.save(foo)
  41. val maybeFound = Foo.caseClassSyncDAO.findOneByID(foo._id)
  42. assertTrue(maybeFound.isDefined)
  43. assertEquals(foo, maybeFound.get)
  44. }
  45. @Test
  46. def testSaveAndFindOneCaseClassWithIntId() {
  47. val foo = FooWithIntId(89, 23, "woohoo")
  48. FooWithIntId.caseClassSyncDAO.save(foo)
  49. val maybeFound = FooWithIntId.caseClassSyncDAO.findOneByID(foo._id)
  50. assertTrue(maybeFound.isDefined)
  51. assertEquals(foo, maybeFound.get)
  52. }
  53. @Test
  54. def testCustomQueryReturnsVariousEntityTypes() {
  55. val foo = Foo(new ObjectId(), 23, "woohoo")
  56. Foo.caseClassSyncDAO.save(foo)
  57. val objects = Foo.customQuery[BObject].toIndexedSeq
  58. assertEquals(1, objects.size)
  59. assertEquals(BInt32(23), objects(0).get("intField").get)
  60. assertEquals(BString("woohoo"), objects(0).get("stringField").get)
  61. val caseClasses = Foo.customQuery[Foo].toIndexedSeq
  62. assertEquals(1, caseClasses.size)
  63. val f = caseClasses(0)
  64. assertEquals(23, f.intField)
  65. assertEquals("woohoo", f.stringField)
  66. }
  67. }