2017-09-29 64 views
2

我使用CAKE 0.21.1.0。将CakeContext传递给另一个.cake文件

我的build.cake脚本加载另一个.cake脚本:tests.cake

tests.cake,我有一个类叫TestRunnerTestRunner有一个称为RunUnitTests()的方法,该方法使用VSTest方法provided by CAKE执行单元测试。

build.cake中,我创建了几个TestRunner的实例。每当我调用的实例中的任何一个RunUnitTests()方法,我看到了以下错误消息:

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

我想这是因为我需要在tests.cake调用VSTestCakeContext明确的实例。

我的问题是:如何确保我的tests.cake脚本共享相同的CakeContext实例作为我的build.cake脚本?我应该怎么做才能编译tests.cake

编辑:

针对devlead's reply,我决定添加更多的信息。

我跟着devlead的建议,改变了我的RunUnitTests()方法签名:

public void RunUnitTests(ICakeContext context) 

build.cake,我的任务之一将执行以下操作:

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

其中TestRunnerAssemblies是只读辞典tests.caketestRunnerName是以前定义的变量。 (在build.cake,我已插入#l "tests.cake"。)

现在我看到此错误消息:

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

我在做什么错?

编辑:

没关系,我需要学习如何更仔细地阅读。而不是通过this,而是通过Context代替,正如devlead最初的建议。现在可以调用RunUnitTests方法而没有问题。

+0

不要使用'this',而是使用'Context'如下所示:https://github.com/cake -contrib/Cake.Recipe/blob/develop/setup.cake#L13以及@devlead示例 –

回答

4

如果RunUnitTests()是一个静态方法或在类中,您需要将上下文作为参数传递给它,如RunUnitTests(ICakeContext context),因为它是一个不同的范围。

然后你可以执行别名作为该方法的扩展。

例子:

RunUnitTests(Context); 

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

例如用类:

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"); 
    } 
} 
+0

谢谢你的帮助,devlead!回复您的回复,我已对自己的帖子进行了一些更新。 –

+0

如果你读过我的第一个例子,不要发送'this'发送'Context'。 – devlead

+1

谢谢你的回复。我需要学习如何更仔细地阅读:-) –