2010-04-19 2 views
1

매개 변수로 void 메소드를 조롱하고 값 매개 변수를 변경하려면 어떻게해야합니까?입력 값을 변경하는 void 메소드 모의

다른 클래스 (SomeClassB)에 대한 종속성이있는 클래스 (SomeClassA)를 테스트하려고합니다. 나는 SomeClassB를 조롱하고 싶다.


private delegate void GetValueDelegate(int x, SomeObject y); 
private void GetValue(int x, SomeObject y) 
{ // process x 
    // prepare a new SomeObject obj 
    SomeObject obj = new SomeObject(); 
    obj.field = x; 
    y = obj; 
} 

내가 쓴 모의 부분에서 :


public class SomeClassA 
{ 
    private SomeClassB objectB;  
    private bool GetValue(int x, object y) 
    { 
     objectB.GetValue(x, y);  // This function takes x and change the value of y 
    } 
} 

SomeClassB 내 단위 테스트 클래스에서 다음 인터페이스 IFoo에게


public interface IFoo 
{ 
    public void GetValue(int x, SomeObject y)  // This function takes x and change the value of y 
} 

pulic class SomeClassB : IFoo 
{ 
    // Table of SomeObjects 
    public void GetValue(int x, SomeObject y) 
    { 
     // Do some check on x 
     // If above is true get y from the table of SomeObjects 
    } 
} 

를 구현, 나는 SomeClassB.GetValue 모방 대리자 클래스를 준비 :


IFoo myFooObject = mocks.DynamicMock(); 
Expect.Call(delegate { myFooObject.Getvalue(5, null); }).Do(new GetValueDelegate(GetValue)).IgnoreArguments().Repeat.Any(); 

SomeObject o = new SomeObject(); 

myFooObject.getValue(5, o); 
Assert.AreEqual(5, o.field); // This assert fails! 

몇 가지 게시물을 확인하고 대리자가 void 메소드를 조롱하는 열쇠가되는 것 같습니다. 그러나 위에서 시도한 후에 작동하지 않습니다. 위임자 클래스에 문제가 있는지 조언 해 줄 수 있습니까? 아니면 모의 선언문에 잘못된 것이 있습니까?


내 RhinoMocks은 3.5 내가 IgnoreArguments()를 포함하는 경우는 마 부분을 삭제처럼 난 그냥이 페이지를 찾을 것 같다 ( http://www.mail-archive.com/[email protected]/msg00287.html

지금은

Expect.Call 변경을 delegate {myFooObject.Getvalue (5, null);}). Do (새 GetValueDelegate (GetValue)). IgnoreArguments().Repeat.Any();

에 Expect.Call (대리인 {) (5, 널 myFooObject.Getvalue}). IgnoreArguments(). Do (새 GetValueDelegate (GetValue)). 반복 .Any();

이제 완벽하게 작동합니다!

+0

귀하의 질문을 이해할 수 있을지 잘 모르겠습니다. IFoo에 의존하는 테스트하려는 메서드를 게시 할 수 있습니까? –

+1

안녕하세요, 귀하의 GetValue 작업을하려면 ref로 표시된 매개 변수가 필요합니다. 작동하는 실제 방법을 게시 할 수 있습니까? – Grzenio

+0

안녕하세요. Darin과 Grzenio 님, 위 질문을 자세히 설명하기 위해 위에 수정했습니다. 미리 감사드립니다! – Kar

답변

4

Kar, 정말 오래된 버전의 .NET을 사용하고 있습니까? 이 구문은 꽤 오랫동안 구식이되었습니다. 나는 또한 당신이 잘못하고 있다고 생각합니다. Rhino Mocks는 마술이 아닙니다. 코드 몇 줄을 추가로 사용하지 않아도됩니다. 예를 들어

내가 그것을 구현할 수

public interface IMakeOrders { 
    bool PlaceOrderFor(Customer c); 
} 

이있는 경우 : 일부 계약자에 대한 쓴

public class TestOrderMaker : IMakeOrders { 
    public bool PlaceOrderFor(Customer c) { 
    c.NumberOfOrders = c.NumberOfOrder + 1; 
    return true; 
    } 
} 

또는

var orders = MockRepository.GenerateStub<IMakeOrders>(); 
orders.Stub(x=>x.PlaceOrderFor(Arg<Customer>.Is.Anything)).Do(new Func<Customer, bool> c=> { 
    c.NumberOfOrders = c.NumberOfOrder + 1; 
    return true; 
}); 

읽기 this intro to RM.

+0

감사합니다. 조지! 네. 여전히 .net 2.0을 사용하고 있습니다 (그래서 3.5로 업그레이드해야합니다.하지만 시간이 좀 걸릴 것입니다 ...) 코드는 매우 깨끗하고 깨끗합니다. 소개에 감사 드리며 정말 도움이됩니다. :) – Kar