C#와 NSubstitute를 사용하여 공개 메서드를 모킹하는 방법
발행: (2026년 1월 6일 오전 11:30 GMT+9)
1 min read
원문: Dev.to
Source: Dev.to
메서드를 virtual 로 만들기
이것이 최소한의 변경이며 NSubstitute에서 완전히 지원됩니다.
public class ProductService
{
public virtual int GetPrice()
{
return 1;
}
}
var service = Substitute.For<ProductService>();
service.GetPrice().Returns(42);
인터페이스 추출 (가장 깔끔한 설계)
가장 좋은 선택입니다.
public interface IProductService
{
int GetPrice();
}
인터페이스를 주입하고 대신 모킹합니다:
var service = Substitute.For<IProductService>();
service.GetPrice().Returns(42);
래퍼 / 어댑터 사용 (타사 또는 레거시 코드용)
public interface IProductServiceWrapper
{
int GetPrice();
}
public class ProductServiceWrapper : IProductServiceWrapper
{
private readonly ProductService _service;
public int GetPrice() => _service.GetPrice();
}
ProductServiceWrapper를 인터페이스와 동일한 방식으로 모킹합니다.