BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Friend Assemblies and Unit Testing

Friend Assemblies and Unit Testing

Bookmarks
One of the major problems with unit testing is the need to access non-public classes and methods. There are numerous ways to work around this such as using proxy classes and reflection, but wouldn't it be nicer if an assembly could just treat non-public fields as if they were public?

C# 2.0 has this ability via friend assemblies. Normally types marked as internal as only accessible from within the assembly that defines it. However, when an assembly says that another assembly is a friend via the InternalsVisibleTo attribute, that second assembly can access any type in the first one that is marked internal.

According to Tim Ng, the ability to define friend assemblies will be added to the next version of Visual Basic.

Rate this Article

Adoption
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Community comments

  • strongly signed assemblies only?

    by andrew mcveigh,

    Your message is awaiting moderation. Thank you for participating in the discussion.

    I may be wrong, but I think this only works for strongly signed assemblies, which takes away some of the usefulness. at least it used to be that way in C#2.0 ...

    Andrew

  • Re: strongly signed assemblies only? - No, that is a documentation error.

    by Jonathan Allen,

    Your message is awaiting moderation. Thank you for participating in the discussion.

    The MSDN documentation is highly inaccurate for this feature. The first error is the implication that the assemblies must be signed. Via testing I just conducted, I found that you do not need signed assemblies to use this feature.

    According to Tim Ng in the linked article, if friend assembly only has to be strongly signed if the assembly being shared is signed.

    One of the rules regarding friend assemblies is that if the declaring assembly is a strong name assembly (that is, that it specifies a key file/container), then you can only declare friends that are also strong name assemblies. This means that you must specify the entire 128 bit public key in the InternalsVisibleTo attribute: InternalsVisibleTo("A, PublicKey=<128-bit Key>").


    The second error I found in the documentation is that it implies your friend assembly has access to "all non-public types". In reality, it only has access to types marked as "internal". Private types and methods remain so.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

BT