2016-08-23 74 views
0

如果我在该类中使用扩展方法,如何用单元测试的接口替换具体类?将接口抽象为具有扩展方法的类

我有一个方法:

[HttpGet] 
[Route("/yoyo/{yoyoId:int}/accounts")] 
public ResponseYoyoEnvelope GetAccountsByYoyoId([FromBody] RequestYoyoEnvelope requestYoyoEnvelope, int yoyoId) 
{ 
    var responseYoyoEnvelope = requestYoyoEnvelope.ToResponseYoyoEnvelope(); 

    // get our list of accounts 
    // responseEnvelope.Data = //list of accounts 
    return responseYoyoEnvelope; 
} 

我想更换:

RequestYoyoEnvelope requestYoyoEnvelope 

与抽象:

IRequestYoyoEnvelope requestYoyoEnvelope 
然而

ToResponseYoyoEnvelope是一个扩展方法。

如果我在该类中使用扩展方法,如何用单元测试的接口替换具体类?

回答

2

假设

public class RequestYoyoEnvelope : IRequestYoyoEnvelope { ... } 

你的扩展方法需要针对接口

public static ResponseYoyoEnvelope ToResponseYoyoEnvelope(this IRequestYoyoEnvelope target) { ... } 

保持行动是因为该模型粘结剂将有问题的结合界面。

在您的单元测试中,您传递RequestYoyoEnvelope的具体实现,并且应该能够测试更新后的扩展方法。

从您的示例中,您不需要接口来测试该方法是否是待测试的方法。只需在模型测试过程中新建一个模型实例并将其传递给该方法即可。

[TestMethod] 
public void GetAccountsByYoyoIdTest() { 
    //Arrange 
    var controller = new YoyoController(); 
    var yoyoId = 123456; 
    var model = new RequestYoyoEnvelope { 
     //you populate properties for test 
    }; 
    //Act 
    var result = controller.GetAccountsByYoyoId(model, yoyoId); 

    //Assert 
    //...do your assertions. 
} 
+0

我调整了我的答案,一旦我意识到我错过了 - 这是一个API端点。然后我读了这个答案 - @Nkosi不会错过它,而且这个答案更重要。 –

4

您可以编写针对接口而不是具体类的扩展方法:

public static class Class2 
{ 
    public static void Extension(this ITestInterface test) 
    { 
     Console.Out.WriteLine("This is allowed"); 
    } 
} 

然后,你可以这样做:

// "Test" is some class that implements the ITestInterface interface 
ITestInterface useExtensionMethod = new Test(); 
useExtensionMethod.Extension(); 

注意过,这还是会工作,即使如果useExtensionMethod不是明确的类型ITestInterface

Test useExtensionMethod = new Test(); 
useExtensionMethod.Extension(); 

这里有controversy关于这是否表示Decorator模式,但请记住Extension方法不是字面上的接口本身的一部分 - “引擎盖下”it's still a static method“,它只是让编译器允许您像实例方法一样对待这个方便。