证明模拟单个方法

时间:2019-01-18 19:15:51

标签: go testing mocking

我很新。我正在尝试使用public class ClassForResults(){ public int UserID { get; set; }; public string User { get; set; } } public IActionResult Search ([FromRoute]string input) { string sqlcon = _iconfiguration.GetSection("ConnectionStrings").GetSection("StringName").Value; List<ClassForResults> results = new List<ClassForResults>(); using (var con = new SqlConnection(sqlcon)) { using (var cmd = new SqlCommand() { CommandText = "SELECT u.UserID, u.User FROM [dbo].[Users] u WHERE User = 'Value';", CommandType = CommandType.Text, Connection = con }) { con.Open(); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { ClassForResults result = new ClassForResults(); result.UserID = reader.GetInt(0); result.User = reader.GetString(1); results.Add(result); } con.Close(); return Ok(new Search(results)); } } } } 模拟struct的单个方法,但是我不知道该怎么做。

代码如下:

testify

这是测试:

type HelloWorlder interface {
    SayHello() string
    GetName() string
}

type HelloWorld struct{}

func (hw *HelloWorld) SayHello() string {
    return fmt.Sprintf("Hello World from %s!", hw.GetName())
}

func (hw *HelloWorld) GetName() string {
    return "se7entyse7en"
}

这个想法是只模拟type MockHelloWorld struct { mock.Mock HelloWorld } func (m *MockHelloWorld) GetName() string { args := m.Called() return args.String(0) } type SomeTestSuite struct { suite.Suite } func (s *SomeTestSuite) TestMocking() { mhw := new(MockHelloWorld) mhw.On("GetName").Return("foo bar") fmt.Println(mhw.SayHello()) } 方法,以便它显示GetName。有可能吗?

对于那些熟悉Python的人来说,我想要实现的目标类似于unittest.Mock类通过Hello World from foo bar!参数所允许的。

更新wraps导入的软件包是这些

testify

1 个答案:

答案 0 :(得分:1)

也许这会对您有所帮助。

package main

import (
    "fmt"
    "github.com/stretchr/testify/mock"
)

type userReader interface {
    ReadUserInfo(int) int
}

type userWriter interface {
    WriteUserInfo(int)
}

type UserRepository struct {
    userReader
    userWriter
}

type realRW struct{}

func (db *realRW) ReadUserInfo(i int) int {
    return i
}

func (db *realRW) WriteUserInfo(i int) {
    fmt.Printf("put %d to db.\n", i)
}

// this is mocked struct for test writer.
type MyMockedWriter struct {
    mock.Mock
}

func (m *MyMockedWriter) ReadUserInfo(i int) int {

    args := m.Called(i)
    return args.Int(0)

}

func main() {
    rw := &realRW{}
    repo := UserRepository{
        userReader: rw,
        userWriter: rw,
    }
    fmt.Println("Userinfo is:", repo.ReadUserInfo(100))
    repo.WriteUserInfo(100)

    // when you want to write test.
    fmt.Println("Begin test....................")
    testObj := new(MyMockedWriter)
    testObj.On("ReadUserInfo", 123).Return(250)

    testRepo := UserRepository{
        userReader: testObj,
        userWriter: rw,
    }
    fmt.Println("Userinfo is:", testRepo.ReadUserInfo(123))
    testRepo.WriteUserInfo(100)
}

// Output:
// Userinfo is: 100
// put 100 to db.
// Begin test....................
// Userinfo is: 250
// put 100 to db.

祝你好运。