Git Product home page Git Product logo

go-mock's Issues

what if the function return a struct, how can i mock it?

package main

import (
	"fmt"

	"github.com/maraino/go-mock"
)

type Infost struct {
	A string
}

type Client interface {
	// Request(url *url.URL) (int, string, error)
	Info() Infost
}

type MyClient struct {
	mock.Mock
}

// func (c *MyClient) Request(url *url.URL) (int, string, error) {
// 	ret := c.Called(url)
// 	return ret.Int(0), ret.String(1), ret.Error(2)
// }

func (c *MyClient) Info() Infost {
	ret := c.Called()
	return ret.GetType(0, Infost{}).(Infost)
}

func main() {
	c := &MyClient{}

	// url, _ := url.Parse("http://www.example.org")
	// c.When("Request", url).Return(200, "{result:1}", nil)
	// // c.When("Request", url).Return(200, "{result:2}", nil)
	// c.When("Request", mock.Any).Return(500, "{result:0}", fmt.Errorf("Internal Server Error")).Times(1)

	// code, json, err := c.Request(url)
	// fmt.Printf("Code: %d, JSON: %s, Error: %v\n", code, json, err)

	// url, _ = url.Parse("http://www.github.com")
	// code, json, err = c.Request(url)
	// fmt.Printf("Code: %d, JSON: %s, Error: %v\n", code, json, err)

	c.When("Info", mock.Any).Return(Infost{"love"})
	info := c.Info()
	fmt.Println(info)

	if ok, err := c.Verify(); !ok {
		fmt.Println(err)
	}
}

panic

panic: Mock call missing for Info()

goroutine 1 [running]:
github.com/maraino/go-mock.(*Mock).Called(0xc420074150, 0x0, 0x0, 0x0, 0x0)
        /gitlab/src/github.com/maraino/go-mock/mock.go:364 +0xf81
main.(*MyClient).Info(0xc420074150, 0xc420041f50, 0x1)
        /github/program-learn/Golang/src/maraino-go-mock/main.go:28 +0x4c
main.main()
        /github/program-learn/Golang/src/maraino-go-mock/main.go:48 +0x172
exit status 2

how to walk over the limits: need use obj as a param to control if it's a mock obj

like below one I have to use obj as a param to mock(control the behavior of QueryResultWithParamObjByPage.But it is not a good way since as the code grows I have to put more useless "obj" to mock.

func (e SparkStatisticsDaoEngine)QueryAggregateMeetingStatistics(xxx,paramObj model.SparkRequestParamObject, session baseDao.Session,obj) ([]interface{}, error) {
session.SetPageSize(paramObj.PageSize)
resultMappingFunc := func(iter baseDao.Iterator) (interface{}, bool) {
var item model.AggregateMeeting
hasNext := iter.Scan(&item.OrgId, &item.AveragePeakNumberOfParticipants)
return item, hasNext
}
param:=xxx
return obj.QueryResultWithParamObjByPage(param)
}

Question [Not a issue]

Hello,
I am not sure how to ask a question, so opening a issue.

I am trying to mock a chain of function calls and i am not really getting how to do it from the documentation. Hope you can help me.

I am mocking redis client ("gopkg.in/redis.v3")

All calls to this API looks something like below

*redis.Client.ZAdd("test", data...).Result()
*redis.Client.ZRem("test", data...).Result()

Result() in ZAdd case belongs to struct *redis.IntCmd and Result() in ZRem case belongs to some other struct

How can I mock these API's ?

Appreciate your help

When using MockFunction.Call, only the first set of return values is returned

The example program below will print "hellohello" instead of "helloworld" - this is because the MockFunction's ReturnValues are not reset between calls. That makes sense when using When and Return, but not when using Call.

package main

import (
	"fmt"

	mock "github.com/maraino/go-mock"
)

type myMock struct {
	mock.Mock
}

func (m myMock) Fn() string {
	r := m.Called()
	return r.String(0)
}

func main() {
	m := myMock{}
	i := 0
	vals := []string{"hello", "world"}
	m.When("Fn").Call(func() string {
		str := vals[i]
		i += 1
		return str
	})
	fmt.Print(m.Fn(), m.Fn())
}

Mock not working

Hi, I'm trying to use this tool but I got no success. See the following snippets and output I got:

func TestMessageSender(t *testing.T) {
        connMock := new(RedisConnMock)
        connMock.When("Close").Return(nil).Times(1)
        connMock.When("Do", "PSTEX", mock.Any, int64(259200000), mock.Any).Return(nil, nil).Times(1)
        connMock.When("Do", "PUBLISH", "SEND_QUEUE", mock.Any).Return(0, nil).Times(1)
--- FAIL: TestMessageSender (0.00 seconds)
panic: Mock call missing for Do(
    "PSETEX",
    "2f9888cf-ca90-3cf4-b4d0-441b66bc03ba",
    int64(259200000),
    "{\"uuid\":\"2f9888cf-ca90-3cf4-b4d0-441b66bc03ba\",\"envelope\":...}",
) [recovered]
    panic: Mock call missing for Do(
    "PSETEX",
    "2f9888cf-ca90-3cf4-b4d0-441b66bc03ba",
    int64(259200000),
    "{\"uuid\":\"2f9888cf-ca90-3cf4-b4d0-441b66bc03ba\",\"envelope\":...}",
)

Can you help me, please?

Support variable number of arguments

I have some use cases for database queries where I want any database query to return an error. The number of arguments changes, so the Any* variables do not work.

My thought was to add a AnyZeroOrMoreArgs (the name should be improved) that would break out of this loop: https://github.com/maraino/go-mock/blob/master/mock.go#L287 along with adjust other required checks. If AnyZeroOrMoreArgs was the only arg passed in to a mock, then it would match any call to a function regardless of how many args are passed in. The AnyZeroOrMoreArgs could also be passed in after specifying some number of args. So for example, if your code takes in a formatting string & a variable number of args after that, you could pass in AnythingOfType("string"), AnymoreArgs.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.