Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

assertion - Scala unit test to check boolean value conversion

I am converting a column containing 1 and 0 to Boolean type and I want to add a test (using assert) if all the 1's are converted to True and all 0's are converted to False. How can I do this?

sourcedf
id    col_int
156   0
157   1

targetdf
id    col_boolean
156   false
157   true
question from:https://stackoverflow.com/questions/65904618/scala-unit-test-to-check-boolean-value-conversion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am using the mapIntToBoolean method to convert 1 and 0 to Boolean, and throw a RuntimeException if the number is not 1 or 0. Then I convert the maps to Set using toSet and use diff to check the differences.

import org.scalatest.funsuite.AnyFunSuite

class IntToBolleanConversionSpec extends AnyFunSuite {
  // one random map
  val map0: Map[Int, Int] = Map((120 -> 1), (121 -> 1), (122 -> 0), (123 -> 0))
  // two maps that suppose to be equal
  val map1: Map[Int, Int] = Map((120 -> 1), (121 -> 1), (122 -> 0), (123 -> 0), (124 -> 1))
  val map2: Map[Int, Boolean] = Map((120 -> true), (121 -> true), (122 -> false), (123 -> false), (124 -> true))

  def mapIntToBoolean(m1: Map[Int, Int]): Map[Int, Boolean] = {
    m1.map { v =>
      val newValue = {
        if (v._2 == 1) true
        else if (v._2 == 0) false
        else {
          new RuntimeException("value is not 1 or 0")
          false
        }
      }
      (v._1 -> newValue)
    }
  }

  test("test map intToBoolean converts correctly") {

    val map3: Map[Int, Boolean] = mapIntToBoolean(map1)
    map3.foreach(println)
    val diff: Map[Int, Boolean] = (map2.toSet diff map3.toSet).toMap
    println("difference must be 0")
    assertResult(0L)(diff.size)

    val map4: Map[Int, Boolean] = mapIntToBoolean(map0)
    map4.foreach(println)
    val diff1: Map[Int, Boolean] = (map2.toSet diff map4.toSet).toMap
    println("difference must be 1")
    assertResult(1L)(diff1.size)
  }
}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...