0

1 つはクラス内のプロパティ、もう 1 つはテスト メソッド内の同等のオブジェクトの 2 つの配列を比較したいと考えています。

オブジェクトは個別に割り当てられるため、メモリの場所が異なるため、直接比較することはできません。

これを回避するために、オブジェクトに説明を実装して、そのプロパティを文字列でリストします: (vel は CGPoint です)

- (NSString *)description {
return [NSString stringWithFormat:@"vel:%.5f%.5f",vel.x,vel.y];
}

私は次のようにテストします:

NSLog(@"moveArray description: %@",[moveArray description]);
NSLog(@"currentMoves description: %@", [p.currentMoves description]);

[[theValue([moveArray description]) should] equal:theValue([p.currentMoves description])];

私の NSLog の収量:

Project[13083:207] moveArray description: (
"vel:0.38723-0.92198"
)

Project[13083:207] currentMoves description: (
"vel:0.38723-0.92198"
)

しかし、私のテストは失敗します:

/ProjectPath/ObjectTest.m:37: error: -[ObjectTest example] : 'Object should pass test' [FAILED], expected subject to equal <9086b104>, got <7099e004>

theValue は KWValue をバイトと目的の C 型で初期化し、その値を次のように設定します。

- (id)initWithBytes:(const void *)bytes objCType:(const char *)anObjCType {
if ((self = [super init])) {
    objCType = anObjCType;
    value = [[NSValue alloc] initWithBytes:bytes objCType:anObjCType];
}

return self;
}

これら 2 つの配列に同じ値のオブジェクトがあることを比較するにはどうすればよいですか?

4

2 に答える 2

3

値ではなくポインター アドレスを比較しているため、テストは失敗します。

1 つの配列を繰り返し処理し、各オブジェクトを 2 番目の配列内の同じ位置にあるオブジェクトと比較できます。比較している値のタイプに対して、比較が正しく行われていることを確認してください。すべての要素のタイプが異なる場合、さらに複雑になります。

// in some class
- (BOOL)compareVelocitiesInArray:(NSArray *)array1 withArray:(NSArray *)array2
{
    BOOL result = YES;

    for (uint i = 0; i < [array1 count]; i++) {
        CustomObject *testObj1 = [array1 objectAtIndex:i]
        CustomObject *testObj2 = [array2 objectAtIndex:i]

        // perform your test here ...
        if ([testObj1 velocityAsFloat] != [testObj2 velocityAsFloat]) {
            result = NO;
        }
    }

    return result;
}

// in another class
NSArray *myArray = [NSArray arrayWithObjects:obj1, obj2, nil];
NSArray *myOtherArray = [NSArray arrayWithObjects:obj3, obj4, nil];
BOOL result;

result = [self compareVelocitiesInArray:myArray withArray:myOtherArray];
NSLog(@"Do the arrays pass my test? %@", result ? @"YES" : @"NO");
于 2011-10-05T23:19:33.850 に答える
0

Kiwi で 2 つの配列の内容が等しいかどうかを比較する別の可能性:

[[theValue(array1.count == array2.count) should] beTrue];
[[array1 should] containObjectsInArray:array2];
[[array2 should] containObjectsInArray:array1];

カウントを比較すると、配列の1つにオブジェクトが複数回含まれていないことが確認されるため、それらが本当に等しいことが確認されます。

于 2015-01-27T09:54:31.107 に答える