Showing posts with label testing. Show all posts
Showing posts with label testing. Show all posts

30 August 2013

Allowing .Net unit tests to access internal members

Good code encapsulation requires that various members be marked as private, or at least internal. However this can make it difficult for unit test frameworks such as NUnit to access them.

You can grant an external (e.g. unit test) assembly access to internal members by doing the following:

  1. Give your test assembly a strong name (via Project Properties, Signing, Sign the assembly)
  2. Compile the assembly (eg. My.Test.dll)
  3. Open the Visual Studio command prompt
  4. Navigate to the folder where My.Test.dll got built
  5. Run:  sn -Tp My.Test.dll
  6. This will display the full public key for the signed assembly. Copy it. (it'll be about 320 chars)
  7. Open the AssemblyInfo.cs file for the assembly containing the code with internals to be tested.
  8. Enter a line such as: [assembly: InternalsVisibleTo("My.Test, PublicKey=1234")] where 1234 is the full key generated in step 6.
Note: this only works if the full key is used, not the shorter summary key.

19 August 2013

How to mock an Angular service for testing

To inject a fake version of myService, and intercept calls to myMethod, do something like this:

Or check out the cool video here.

    var myMethodFake = function() { ... };

    beforeEach(function () {
        module(function ($provide) {
            mockMyService = {
                myMethod: jasmine.createSpy('myMethod').andCallFake(myMethodFake)
            };
            $provide.value('myService', mockMyService);
        });
    });

    it('does stuff', inject(function(myService) {
       myService.myMethod();
    });