Search code examples
c#cakebuild

Passing CakeContext to another .cake file


I use CAKE 0.21.1.0.

My build.cake script loads another .cake script: tests.cake.

In tests.cake, I have a class called TestRunner. TestRunner has a method called RunUnitTests(), which executes unit tests using the VSTest method provided by CAKE.

In build.cake, I create several instances of TestRunner. Whenever I invoke the RunUnitTests() method on any one of the instances, I see the following error message:

error CS0120: An object reference is required for the non-static field, method, or property 'VSTest(IEnumerable<FilePath>, VSTestSettings)'

I think this is because I need to call VSTest on an explicit instance of CakeContext in tests.cake.

My question is: How can I ensure that my tests.cake script shares the same CakeContext instance as my build.cake script? What should I do to get tests.cake to compile?

EDIT:

In response to devlead's reply, I have decided to add more information.

I followed devlead's suggestion and changed my RunUnitTests() method signature to:

public void RunUnitTests(ICakeContext context)

In build.cake, one of my tasks does the following:

TestRunner testRunner = TestRunnerAssemblies[testRunnerName];
testRunner.RunUnitTests(this);

where TestRunnerAssemblies is a read-only dictionary in tests.cake, and testRunnerName is a previously-defined variable. (In build.cake, I have inserted #l "tests.cake".)

Now I see this error message:

error CS0027: Keyword 'this' is not available in the current context

What am I doing wrong?

EDIT:

Never mind, I need to learn how to read more carefully. Instead of passing in this, I passed in Context instead, as devlead originally suggested. Now the RunUnitTests method can be invoked without issue.


Solution

  • If RunUnitTests() is a static method or in a class you'll need to pass the context as an parameter to it like RunUnitTests(ICakeContext context) because it's a different scope.

    And then you can execute aliases as an extension on that methods.

    Example:

    RunUnitTests(Context);
    
    public static void RunUnitTests(ICakeContext context)
    {
        context.VSTest(...)
    }
    

    Example with class:

    Task("Run-Unit-Tests")
        .Does(TestRunner.RunUnitTests);
    
    RunTarget("Run-Unit-Tests");
    
    
    public static class TestRunner
    {
        public static void RunUnitTests(ICakeContext context)
        {
            context.VSTest("./Tests/*.UnitTests.dll");
        }
    }