Unit testing static utility class

时间:2016-02-12 21:42:57

标签: c# .net mocking moq

How can I unit test static method within a static class?

Having this code:

private void KeysDown(object sender, KeyEventArgs e)
{
    if (e.VirtualKey == VirtualKey.Enter)
    {
        //do something
    }
}

I'm working with 3rd party library and the only thing I can modify is AddressConverter class. By the way, BillingAddress() is a 3rd party library, when decompiled shows this:

public class AddressConverter {
    public static BillingAddress ConvertAddress(ShippingAddress address)
    {
        var billingAddress = new BillingAddress (); // this is the problem - 3rd party lib
        ...
}

The problem is that I can't create // decompiled code public class BillingAddress : IOrderAddress { public BillingAddress() : base(SomeSessionContext.Current.Class) { ... because it's values are taken from some session variable etc.

How can I test this? Any workarounds?

2 个答案:

答案 0 :(得分:2)

如果您无法重构将BillingAddress注入静态方法,则可以使用Microsoft Fakes来测试它。

基本上你会为你的第三方DLL添加一个Fakes库:

  

Solution Explorer 中,打开您的单元测试项目的参考和   选择包含所需方法的程序集的引用   假的。 ...选择添加假装大会

enter image description here

然后你应该可以使用ShimBillingAddress。 (航空代码警告,我无法访问您的第三方lib :-))

using (ShimsContext.Create())
{
     // Arrange:
     YourThirdPartyLib.Fakes.ShimBillingAddress.SomeMethod = () => { return "some meaningful value"; };

     // Instantiate the component under test:
     var sut = new AddressConverter();

     // Act:
     var result = sut.ConvertAddress(someShippingAddress);

     // Assert: 
}

来自MSDN - Isolating Code Under Test with Microsoft Fakes // Getting started with shimsMSDN - Using shims to isolate your application from other assemblies for unit testing的报价和说明。

MSDN上有关于假货产生的垫片naming conventions的信息,因为它并不总是很明显。

另外,this answer的后半部分有关于为系统dll设置伪造的演练。

答案 1 :(得分:1)

Do not create BillingAddress inside AddressConverter. Use an extra argument for ConvertAddress or remove the static keyword and use an BillingAddressFactory to create a new instance of IOrderAddress.