我想用反射实现 Go 接口以生成模拟和存根。但是如果我查看反射包,我不知道该怎么做(也许不可能)。
示例:测试 func 调用ResponseWriterWriteHeader(404)
:
type ResponseWriterMock struct { //
status int //
} // How to replace
func (*ResponseWriterMock) Header() Header {} // this block with
func (*ResponseWriterMock) Write([]byte) (i int, e error) {} // a reflectivly
func (m *ResponseWriterMock) WriteHeader(status int) { // generated mock?
m.status = status //
} //
responseWriterMock := new(ResponseWriterMock)
funcToTest(responseWriterMock)
if responseWriterMock.status != 404 {
// report error
}
使用 RhinoMocks (C#) 我会这样写:
var responseWriterMock = MockRepository.GenerateMock<ResponseWriter>();
funcToTest(responseWriterMock);
responseWriterMock.AssertWasCalled(rw => rw.WriteHeader(404));
如何使用反射实现 Go 接口?
附录