BLOG main image
분류 전체보기 (239)
Rails (65)
Ruby (34)
이야기 (40)
스토리큐 (61)
그 밖에.. (30)
C# (6)
작은아이의 생각
agiletalk's me2DAY
[rails] Growl4Rails
美소년 ㅇㅅㅇ씨의 一日
마사키군의 생각
ayukawa's me2DAY
작은아이의 생각
agiletalk's me2DAY
[Google App Engine] 나의 첫번..
머드초보의 블로그
54,048 Visitors up to today!
Today 14 hit, Yesterday 47 hit

 SUBSCRIBE

2009/05/19 05:53

moq를 사용하기 위해서는 메소드가 추상 메소드이어야 한다. 즉 virtual로 선언되어 있거나 interface 안에 선언되어 있어야 한다. moq를 이용해서 TcpClient와 같은 System class를 직접 mocking할 수는 없다. TcpClient를 mocking하는 한 가지 방법은 Adapter 패턴 을 사용하는 것이다.

  1. public interface ITcpClient
  2. {
  3.   void Connect(string host, int port);
  4.   Stream GetStream();
  5. }
  6. public class TcpClientAdapter : ITcpClient
  7. {
  8.   private readonly TcpClient _client;
  9.   public TcpClientAdapter(TcpClient tcpClient)
  10.   {
  11.     _client = tcpClient;
  12.   }
  13.   public void Connect(string host, int port)
  14.   {
  15.     _client.Connect(host, port);
  16.   }
  17.   public Stream GetStream()
  18.   {
  19.     return _client.GetStream();
  20.   }
  21. }

이제 TcpClient 클래스 대신 ITcpClient 인터페이스를 moq에서 사용할 수 있다.

  1. var tcpClientMock = new Mock<ITcpClient>();
  2. var streamMock = new Mock<Stream>();
  3. streamMock.Setup(stream => stream.ReadByte()).Returns(0x03);
  4. tcpClientMock.Setup(tcp => tcp.GetStream()).Returns(streamMock.Object);

더 좋은 방법은 없을까?