模拟和接口实现

Mocking and interface implementation

我有 c# net 项目并使用 nunit 进行测试。

我有一个名为 xyz 的 class,它实现了会话 class。会话 class 是一个内置的 class,它是我在项目中引用的 dll 的一部分。

我需要在我的测试项目中模拟会话 class。当我尝试模拟会话 class 时,我收到一条错误消息,提示您只能模拟可重写的方法或接口。

所以我想实现一个 class 来扩展会话 class,然后为那个 class 创建一个接口。然后我会模拟接口并调用 base class 方法。这听起来是个不错的解决方案还是有人有更好的主意?

创建一个接口,比如 ISessionService。在此接口中添加您需要模拟的所有方法。创建一个实现此接口的 class SessionManager。在这个方法的实现中调用实际的方法。现在您可以使用接口模拟方法。

public class xyz : ISessionService
    {
        public string AddCustomer(AddCustomerRequest addCustomerRequest)
        {   
            using (SessionService service = new SessionService())
            { 
                response = service.AddCustomer(addCustomerRequest);
            }
            return response;
        }
}