测试:: MockModule需要用“的getType'方法返回一个对象数组 [英] Test::MockModule needs to return an array of objects with a 'getType' method

查看:234
本文介绍了测试:: MockModule需要用“的getType'方法返回一个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使Perl的code单元测试来嘲笑返回包含这也需要加以嘲笑,因为他们有一个方法GetType(),我需要模拟对象的数组的服务。

I'm attempting to make a unit test for perl code to mock a service which returns an array containing objects which also need to be mocked because they have a method getType() which I need to mock.

所以,code,其处理该服务调用的结果看起来是这样的:

So the code which processes the results of this service call looks something like this:

   foreach my $set (@{$serviceResults->getValue()}) {
      next unless ($set->getType() eq 'type');
      ...
   }

和我试图嘲弄的服务,像这样:

and I'm trying to mock the service like so:

my $service;
my $mockService = sub {
    my (%resultValues) = @_;
    $service = mockModule(
       'My::Service',
       getValue => createMockObject(
          # how to mock the getType method?
       )
    )
};

然后我创建这样一个模拟:

And then I create a mock like this:

$mockService->([
    {type=>'a', data=>[0, 5]},
    {type=>'b', data=>[2, 3]}]);

那么,如何创建数组中的每个哈希对象的getType方法的模拟?此数组取决于单元测试的变化,我不能用一个固定大小的数组。

So how do I create the mock of the getType method on each hash object in the array? This array changes depending on the unit test, I can't use a fixed size array.

推荐答案

你有没有看着类::微小?它提供了一个非常小的,轻量级的对象。

Have you looked into Class::Tiny? It offers a very minimal, light-weight object.

use strict;
use warnings;
use feature qw( say );

package Mockable;

use Class::Tiny qw( getType );

package main;

my $foo = Mockable->new(
    getType => 'ZZZ',
);
say $foo->getType;    # prints ZZZ

这会嘲笑你需要的方法。如果你需要的东西更重,你也可以考虑使用来创建一个小班级,从刚创建对象这个类有你需要的访问者。

This will mock the method you require. If you need something heavier, you could also look into using Moo to create a small class and just creating objects from this class which have the accessors you need.

这篇关于测试:: MockModule需要用“的getType'方法返回一个对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆