14

我想知道最好的方法是什么......我有兴趣将 PostSharp 引入我的一个项目,但我不确定如何正确地对标有属性的类进行单元测试。

例如:

public class hello {

    [MyAspectThatDoesSomethingToTheDatabaseWhenThisMethodGetsCalled]
    public int omg(string lol) {
        //fancy logic in here
    }
}

我想测试 omg() 方法中的逻辑,但在单元测试中我需要确保不会调用方面,因为实际上并没有数据库。

想法?

4

7 回答 7

3

I'm not entirely sure how postsharp works, but as I currently understand, you invoke a post build process to weave the aspects into the IL.

If my understanding is correct and if you can skip the post-build weaving then you should be testing your method in ignorance of the aspect ( and testing the aspect separately somewhere else ).

Why?

If you test the aspect and the method, you are testing 3 things at once:

  1. the method
  2. the aspect
  3. the weaving of the aspect into the code

This is bad karma and may lead you down the rabbit hole if something goes wrong ( as well as making your unit test into an integration test ).

Looking at the list above:

  • you do need to test the method, in isolation with no other distractions as this will let you focus on making sure the method does exactly what you expect - no more, no less.
  • you don't need to test the aspect every time it is used, just test it once and make sure it does what you think it does
  • you don't need to test that the weaving works; it is ( should be ) tested as part of the post sharp implementation.
于 2010-03-07T19:31:56.187 回答
3

我的意见是,您应该像手动编码方面一样测试代码——即测试方法的全部功能,包括方面实现的功能。

该问题现在记录在 PostSharp 在线文档中,网址为http://doc.postsharp.net/postsharp-3.0/Content.aspx/PostSharp-3.0.chm/html/2ad6cf92-08eb-4537-a434-d88a3e493721.htm

于 2010-02-13T18:49:05.380 回答
2

如果您想编写纯 UNIT 测试,请考虑在 UNIT TESTING 构建期间通过在项目中设置编译符号“SkipPostSharp”或设置 MSBuild 属性“SkipPostSharp=True”来禁用模块的 PostSharp。

如果您乐于进行集成测试,您可以测试您的方法和 PostSharp 属性的全部功能,包括数据库访问(如Gael 所建议)。

于 2011-12-10T23:59:25.883 回答
1

为了在我的代码中关闭与数据库相关的方面,我引入了一个名为 TestingEnvironment 的静态类,它具有一个名为 TurnOffAspects 的布尔属性。aspect 中的代码检查此属性,如果将其设置为“true”,则 aspect 返回而不做任何事情。在测试设置期间,我将 TestingEnvironment.TurnOffAspects 属性设置为 true,在测试拆解期间,设置回 false。当然,您可以让事情变得更细化,为您拥有的每个方面引入一个属性。您应该非常谨慎地选择关闭哪些方面,因为它会对您的测试产生很大影响,并且即使测试通过也会使您的生产代码失败。

于 2011-03-01T08:35:08.683 回答
1

我不同意盖尔的观点。我从一个朋友那里了解到,我必须测试我要编写的代码,而且通常只测试一次。

于 2010-03-07T13:42:29.573 回答
0

可能您可以使用依赖注入并为切面类引入一个静态属性,您可以在其中决定将使用哪种数据库访问提供程序(例如使用工厂),在测试范围内设置假的。

于 2010-02-10T20:26:47.797 回答
0

我目前的方法是让测试作为我们 TFS 上构建过程的一部分运行。这可能对所有场景都没有帮助,但我花了很长时间才找到一个解决方案,该解决方案允许我运行业务逻辑的单元测试,而不受 PostSharp 的任何影响。

我创建了两个不同的构建定义,其中一个将 MSBuild Arguments 设置为/p:SkipPostSharp=True(这是运行单元测试的那个),另一个False分别设置为。另外,我使用 PostSharp 将Disable Tests选项设置True为构建定义。

我知道这并不理想(特别是因为现在我遇到了无法在没有任何更改的情况下在本地运行测试的问题),但我找不到任何其他方法。似乎遇到同样问题的人并不多。由于我是 MSBuild 及其配置方面的绝对新手,也许有更好知识的人可以提供帮助。

我还Configuration Manager尝试在 Visual Studio 中创建另一个构建定义,但我所有的尝试只产生了比其他任何东西更多的问题。

于 2012-12-11T16:09:02.800 回答