1

我正在尝试使用 gomock 模拟以下方法

func (w *writer) Publish(vacancies []model.Vacancy) error {
    ...

    if _, err = w.conn.WriteMessages(msg); err != nil {
        return fmt.Errorf("failed to write message: %w", err)
    }

界面:

type Producer interface {
        Publish(vacancies []model.Vacancy) error
        Close() error
    }

套件测试:

func (p *ProducerTestSuite) SetupTest() {
    p.mockCtrl = gomock.NewController(p.T())
    p.producer = NewMockProducer(p.mockCtrl)
    writer, err := producer.NewWriter(context.Background(), scheduler.KafkaConf{Addr: "localhost:9092", Topic: "test"})
    p.Require().NoError(err)
    p.writer = writer
}
...
func (p *ProducerTestSuite) TestProducer_Publish() {
    p.producer.EXPECT().Publish([]model.Vacancy{}).Return(nil)
    p.Require().NoError(p.writer.Publish([]model.Vacancy{}))
}

模拟:

//go:generate mockgen -package producer_test -destination mock_test.go -source ../kafka.go

当我尝试运行测试时,我收到了这条消息:

=== RUN   TestSuite/TestProducer_Publish
    controller.go:137: missing call(s) to *producer_test.MockProducer.Publish(is equal to [] ([]storage.Vacancy)) /Users/...
    controller.go:137: aborting test due to missing call(s)

我哪里错了?

4

1 回答 1

0

看起来好像你没有调用你所期望的相同的东西。您的期望正在观看p.producer.Publish(),但您的测试代码调用p.writer.Publish()。我在这里看不到任何会导致writer调用任何内容的代码producer

以下代码的行为与您预期的一样:

func (p *ProducerTestSuite) TestProducer_Publish() {
    p.producer.EXPECT().Publish([]model.Vacancy{}).Return(nil)
    p.Require().NoError(p.producer.Publish([]model.Vacancy{}))
}

然而,这个测试似乎并没有真正执行测试名称表明它应该执行的单元。也许你对嘲讽有误解?

于 2021-08-16T09:27:11.773 回答