当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Constrain PEX code-under-test to a single method?

问题描述:

Can the code-under-test in PEX be constrained to a single method? I am aware you can constrain it to assemblies and classes, but what about members?

I am essentially trying to achieve 100% code coverage for the following method:

public virtual bool GetLastSymbol(string symbolHint, out string symbol)

{

if (symbolHint == null)

{

throw new ArgumentNullException("symbolHint");

}

IEnumerable<string> symbols;

symbol = this.VariableHints.TryGetValue(symbolHint, out symbols) ? symbols.Last() : null;

return symbol != null;

}

The following PUT achieves 12/15 code coverage, because Im only testing for 1 of the possible 2 values it can return:

found = symbolManager.GetLastSymbol(symbolHint, out symbol);

PexAssert.IsFalse(found);

To achieve full coverage for this PUT, I need to change the objects state so that the method hits both branches. I could satisfy this by using separate PUTs using a factory method to setup the different states, but this would leave me with 2 PUTs with incomplete code coverage, rather than 1 PUT with full coverage. I realise in theory the 2 PUTs would have a combined coverage of 100%, but I need that 100% figure in practice so I can setup CI properly.

So, to reach the other branch in the same PUT, I must append the following code to the above 2 lines:

symbolManager.CreateSymbol(symbolHint); // Ensure next call returns true.

found = symbolManager.GetLastSymbol(symbolHint, out symbol);

PexAssert.IsTrue(found);

Presumably the code coverage for the GetLastSymbol method is now 100%, but because Ive introduced another method call to the type under test, the code coverage now drops to 20/29.

How can I constrain a PUT to only measure code coverage for a single method? I realise I may have misunderstood this metric entirely, so please explain why if this is the case :)

网友答案:

The 'PEX API Reference' which comes installed with PEX was useful for solving this:

The Microsoft.Pex.Framework.Coverage namespace includes several filter attributes which can exclude various facets from effecting code coverage. The one I wanted was:

PexCoverageFilterMethodAttribute

Using this method I was able to remove the CreateSymbol method from the coverage report:

[PexCoverageFilterMethod(PexCoverageDomain.UserOrTestCode, "CreateVariable")]

This now increased my code coverage to 13/15; higher than before, but still not the 100% I was expecting. Long story short, I discovered PEX was including the constructor in the coverage reports too...

[PexCoverageFilterMethod(PexCoverageDomain.UserOrTestCode, "ctor")]

I'm now receiving 13/13 for my code coverage. I'm a happy bunny :)

分享给朋友:
您可能感兴趣的文章:
随机阅读: