The Programmers Book

Scala project with scalatest


In this Article, we are going to lean how to create scala project with sbt in IntellijIDEA.

And also we will learn how to test this scala project with scalatest jar.

Technologies used are

  1. IntellijIDEA 2018.3.2(Community Edition)
  2. Scala 2.11.7
  3. Sbt 1.3.3
  4. Scalatest 3.0.0

Let start now…

Create a scala project with IntellijIDEA.

Select File -> New -> New Project

Now select Scala on the Left window and   sbt on the right windows and then click on the Next button.

Give project name in the Name field and then click on the Finish button.

The above Project Structure will be created.

  • Create package name.
com.theprogrammersbook
  • Check the build.sbt that it has correct version .

In this project we used the following version.

 name := "ScalaTestExample"

version := "0.1"

scalaVersion := "2.11.7"  
  • Create a Topping case class
 case class Topping(name :String)
  • Create a Pizza Class.
 package com.theprogrammersbook

import scala.collection.mutable.ArrayBuffer

class Pizza {
     // save topping
  private val toppings = new ArrayBuffer[Topping]()
  def addTopping (t :Topping) {toppings+=t}
  def removeTopping (t: Topping) {toppings-=t}
  def getToppings() = toppings.toList

  def boom {throw new Exception("Boom!")}
}
 

 We have created required classes to test this application.

  • Add scalatest jar file to build.sbt file.
 libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.0" % Test 
  • Create a  test class in src/test/scala  as PizzaTest
 package com.theprogrammersbook

import org.scalatest.{BeforeAndAfter, FunSuite}

class PizzaTest  extends FunSuite with BeforeAndAfter{
  test("checking 1 equals to 1"){
        assert(1==1)
  }
  var pizza : Pizza = _
  before{
  pizza = new Pizza
  }
  // testing the size of topping.
  test("initial size of pizza"){
       assert(pizza.getToppings().size==0)
  }
  test("adding topping to pizza"){
       pizza.addTopping(Topping("green olives"))
    assert(pizza.getToppings().size==1)
  }
  test("remove the topping"){
    pizza.removeTopping(Topping("green olives"))
         assert(pizza.getToppings().size==0)
  }
}
 
  • Run this Test .

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *