title: How to do Unit Testing with gorm
body: <p>I'm new in <code>Go</code> and <code>unit test</code>. In my project am using <code>Go</code> with <code>gorm</code> and connecting <code>mysql</code> database.</p>
  <p>my queries is how to unit test my code:</p>
  <p><strong>My code is below(main.go):</strong></p>
  <pre><code>package main
  
  import (
      &quot;encoding/json&quot;
      &quot;fmt&quot;
      &quot;net/http&quot;
      &quot;strconv&quot;
      &quot;time&quot;
  
      &quot;github.com/gorilla/mux&quot;
      &quot;github.com/jinzhu/gorm&quot;
      _ &quot;github.com/jinzhu/gorm/dialects/mysql&quot;
  )
  
  type Jobs struct {
      JobID                  uint   `json: &quot;jobId&quot; gorm:&quot;primary_key;auto_increment&quot;`
      SourcePath             string `json: &quot;sourcePath&quot;`
      Priority               int64  `json: &quot;priority&quot;`
      InternalPriority       string `json: &quot;internalPriority&quot;`
      ExecutionEnvironmentID string `json: &quot;executionEnvironmentID&quot;`
  }
  
  type ExecutionEnvironment struct {
      ID                     uint      `json: &quot;id&quot; gorm:&quot;primary_key;auto_increment&quot;`
      ExecutionEnvironmentId string    `json: &quot;executionEnvironmentID&quot;`
      CloudProviderType      string    `json: &quot;cloudProviderType&quot;`
      InfrastructureType     string    `json: &quot;infrastructureType&quot;`
      CloudRegion            string    `json: &quot;cloudRegion&quot;`
      CreatedAt              time.Time `json: &quot;createdAt&quot;`
  }
  
  var db *gorm.DB
  
  func initDB() {
      var err error
      dataSourceName := &quot;root:@tcp(localhost:3306)/?parseTime=True&quot;
      db, err = gorm.Open(&quot;mysql&quot;, dataSourceName)
  
      if err != nil {
          fmt.Println(err)
          panic(&quot;failed to connect database&quot;)
      }
      //db.Exec(&quot;CREATE DATABASE test&quot;)
      db.LogMode(true)
      db.Exec(&quot;USE test&quot;)
      db.AutoMigrate(&amp;Jobs{}, &amp;ExecutionEnvironment{})
  }
  
  func GetAllJobs(w http.ResponseWriter, r *http.Request) {
      w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
      fmt.Println(&quot;Executing Get All Jobs function&quot;)
  
      var jobs []Jobs
      if err := db.Select(&quot;jobs.*, execution_environments.*&quot;).Joins(&quot;JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id&quot;).Find(&amp;jobs).Error; err != nil {
          fmt.Println(err)
      }
      fmt.Println()
      if len(jobs) == 0 {
          json.NewEncoder(w).Encode(&quot;No data found&quot;)
      } else {
          json.NewEncoder(w).Encode(jobs)
      }
  }
  
  // create job
  func createJob(w http.ResponseWriter, r *http.Request) {
      w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
      fmt.Println(&quot;Executing Create Jobs function&quot;)
      var jobs Jobs
      json.NewDecoder(r.Body).Decode(&amp;jobs)
      db.Create(&amp;jobs)
      json.NewEncoder(w).Encode(jobs)
  }
  
  // get job by id
  func GetJobById(w http.ResponseWriter, r *http.Request) {
      w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
      params := mux.Vars(r)
      jobId := params[&quot;jobId&quot;]
  
      //var job []Jobs
      //db.Preload(&quot;Items&quot;).First(&amp;job, jobId)
      var jobs []Jobs
      var executionEnvironments []ExecutionEnvironment
      if err := db.Table(&quot;jobs&quot;).Select(&quot;jobs.*, execution_environments.*&quot;).Joins(&quot;JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id&quot;).Where(&quot;job_id =?&quot;, jobId).Find(&amp;jobs).Scan(&amp;executionEnvironments).Error; err != nil {
          fmt.Println(err)
      }
  
      if len(jobs) == 0 {
          json.NewEncoder(w).Encode(&quot;No data found&quot;)
      } else {
          json.NewEncoder(w).Encode(jobs)
      }
  }
  
  // Delete Job By Id
  func DeleteJobById(w http.ResponseWriter, r *http.Request) {
      params := mux.Vars(r)
      jobId := params[&quot;jobId&quot;]
  
      // check data
      var job []Jobs
      db.Table(&quot;jobs&quot;).Select(&quot;jobs.*&quot;).Where(&quot;job_id=?&quot;, jobId).Find(&amp;job)
      if len(job) == 0 {
          json.NewEncoder(w).Encode(&quot;Invalid JobId&quot;)
      } else {
  
          id64, _ := strconv.ParseUint(jobId, 10, 64)
          idToDelete := uint(id64)
  
          db.Where(&quot;job_id = ?&quot;, idToDelete).Delete(&amp;Jobs{})
          //db.Where(&quot;jobId = ?&quot;, idToDelete).Delete(&amp;ExecutionEnvironment{})
  
          json.NewEncoder(w).Encode(&quot;Job deleted successfully&quot;)
          w.WriteHeader(http.StatusNoContent)
      }
  
  }
  
  // create Execution Environments
  func createEnvironments(w http.ResponseWriter, r *http.Request) {
      w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
      fmt.Println(&quot;Executing Create Execution Environments function&quot;)
      var executionEnvironments ExecutionEnvironment
      json.NewDecoder(r.Body).Decode(&amp;executionEnvironments)
      db.Create(&amp;executionEnvironments)
      json.NewEncoder(w).Encode(executionEnvironments)
  }
  
  // Get Job Cloud Region
  func GetJobCloudRegion(w http.ResponseWriter, r *http.Request) {
      w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
      fmt.Println(&quot;Executing Get Job Cloud Region function&quot;)
  
      params := mux.Vars(r)
      jobId := params[&quot;jobId&quot;]
  
      //var jobs []Jobs
      var executionEnvironment []ExecutionEnvironment
  
      db.Table(&quot;jobs&quot;).Select(&quot;execution_environments.*&quot;).Joins(&quot;JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id&quot;).Where(&quot;jobs.job_id =?&quot;, jobId).Find(&amp;executionEnvironment)
  
      var pUuid []string
      for _, uuid := range executionEnvironment {
          pUuid = append(pUuid, uuid.CloudRegion)
      }
      json.NewEncoder(w).Encode(pUuid)
  
  }
  
  func main() {
      // router
      router := mux.NewRouter()
      // Access URL
      router.HandleFunc(&quot;/GetAllJobs&quot;, GetAllJobs).Methods(&quot;GET&quot;)
      router.HandleFunc(&quot;/createJob&quot;, createJob).Methods(&quot;POST&quot;)
      router.HandleFunc(&quot;/GetJobById/{jobId}&quot;, GetJobById).Methods(&quot;GET&quot;)
      router.HandleFunc(&quot;/DeleteJobById/{jobId}&quot;, DeleteJobById).Methods(&quot;DELETE&quot;)
  
      router.HandleFunc(&quot;/createEnvironments&quot;, createEnvironments).Methods(&quot;POST&quot;)
      router.HandleFunc(&quot;/GetJobCloudRegion/{jobId}&quot;, GetJobCloudRegion).Methods(&quot;GET&quot;)
  
      // Initialize db connection
      initDB()
  
      // config port
      fmt.Printf(&quot;Starting server at 8000 \n&quot;)
      http.ListenAndServe(&quot;:8000&quot;, router)
  }
  </code></pre>
  <p>I try to create unit test file below, but it is not running it shows like this
  <a href="https://i.stack.imgur.com/Kymus.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kymus.png" alt="enter image description here" /></a></p>
  <p><strong>main_test.go:</strong></p>
  <pre><code>package main
  
  import (
      &quot;log&quot;
      &quot;os&quot;
      &quot;testing&quot;
  
      &quot;github.com/jinzhu/gorm&quot;
      _ &quot;github.com/jinzhu/gorm/dialects/mysql&quot;
  )
  
  func TestinitDB(m *testing.M) {
      dataSourceName := &quot;root:@tcp(localhost:3306)/?parseTime=True&quot;
      db, err := gorm.Open(&quot;mysql&quot;, dataSourceName)
  
      if err != nil {
          log.Fatal(&quot;failed to connect database&quot;)
      }
      //db.Exec(&quot;CREATE DATABASE test&quot;)
      db.LogMode(true)
      db.Exec(&quot;USE test111&quot;)
      os.Exit(m.Run())
  }
  </code></pre>
  <p>Please help me to write unit test file</p>