Say I have a code snippet that should be covered with the unit-tests:
func selfIntroductionMessage(ctx context.Context, errorC chan error) *routing.Message {
msg := &routing.Message{}
if emissionTime, err := ptypes.TimestampProto(time.Now()); err != nil {
select {
case errorC <- fmt.Errorf("Couldn't convert time to google.protobuf.Timestamp: %v", err):
case <-ctx.Done():
}
return nil
} else {
msg.EmissionTime = emissionTime
}
return msg
}
Hopefully ptypes.TimestampProto(time.Now())
will never fail under normal conditions, but since ptypes.TimestampProto
always returns error return, it's worth checking it.
The common approach to solve this problem is to mock every dependency: time.Now()
should be replaced with the function of same interface. But when one starts to mock standard library, application code quickly becomes ugly.
So I wonder if it's possible to replace time.Now()
implementation to erroneous for unit-testing purposes using the reflect
package.
Aucun commentaire:
Enregistrer un commentaire