Mocked method not working in golang while running the test cases

63 views
Skip to first unread message

prakash sharma

unread,
Jan 11, 2020, 10:24:33 AM1/11/20
to golang-nuts
Need help:

I am trying to mock an struct method in test cases but it is not working. I want to mock Validate method here: 
package main

import (
   
"fmt"
)

type
DemoInterface interface {
   
Inc(int) (int, error)
   
Validate(int) error
}
type
DemoStruct struct{}

func
(l DemoStruct) Inc(num int) (int, error) {
    err
:= l.Validate(num)
   
if err != nil {
       
return 0, err
   
}
    num
= num + 100
   
return num, nil

}
func
(l DemoStruct) Validate(num int) error {// SOME DB LOGIC IS HERE WHICH I CAN NOT POST at Stackoverflow
   
if num > 100 {
       
return fmt.Errorf("INVALID NUM %v", num)
   
}
   
return nil
}

func main
() {
    s
, err := DemoStruct{}.Inc(10)
   
if err != nil {
        fmt
.Println(err)
   
}
    fmt
.Println(s)

}


My test cases:
package main

import (
    "fmt"
    "testing"
)

const (
    SUCCESS = "SUCCESS"
    ERROR   = "ERROR"
)

type MockDemoStruct struct {
    DemoStruct
    functionality string
}

func (m MockDemoStruct) Validate(num int) error {
    switch m.functionality {
    case SUCCESS:
        return nil
    case ERROR:
        fmt.Errorf("MOCK ERROR %v", num)

    }
    return fmt.Errorf("MOCK ERROR %v", num)
}

func TestPath(t *testing.T) {

    t.Run("ERROR", func(t *testing.T) {
        ls := MockDemoStruct{DemoStruct{}, SUCCESS}
        res, err := ls.Inc(110)
        expected := fmt.Errorf("MOCK ERROR %v", 10)
        if err != expected {
            t.Errorf("NOT MATCH  %v  %v", err, expected)
            //-----------------NOT MATCH  INVALID NUM 110  MOCK ERROR 10 ERROR-----------------------------

        }
        fmt.Println(res)
    })
}


Chris Burkert

unread,
Jan 11, 2020, 11:10:23 AM1/11/20
to prakash sharma, golang-nuts
You could inject your dependencies. There is a funny talk by Liron Levin [1] which helped me a lot.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/a90f9eee-cebb-4d2d-b1cf-76b16faee296%40googlegroups.com.

prakash sharma

unread,
Jan 12, 2020, 11:49:12 AM1/12/20
to Chris Burkert, golang-nuts
Thanks for your help Chris
Introduced dependency injection in this code using Delegation Design pattern with the help of interface.

Here's the details explanation
Please share yours feedback.

Reply all
Reply to author
Forward
0 new messages