Dark Hippo
Dark Hippo

Reputation: 1265

Unit test not showing as covering method

In one of my unit test classes, I'm doing several tests that test the response of a method. They're very similar tests, so I've created a private method to avoid writing out basically the same test multiple times (I'm lazy).

The problem is, in Visual Studio, the "passing" information above the method itself isn't showing the coverage from those unit tests that call the private method.

Example method

Simple example method

Example unit tests

enter image description here

As you can see, the unit tests all call MethodForTesting1, though only the first unit test, the one that calls it directly, is seen to cover the method.

Is there any way around this, or do the Visual Studio testing tools just not like private methods in unit tests?

EDIT Quick addition, I'm new to unit testing, so for bonus points, is there a better way to gauge code coverage when looking through a class?

EDIT 2 To address those quick answers who points out that I forgot the [TestMethod] above the last method, it still doesn't show code coverage

enter image description here

Upvotes: 3

Views: 5771

Answers (3)

Shah
Shah

Reputation: 1399

Ideally, your unit tests should be written as below:

    [TestMethod]
    public void TestMethod21()
    {
        Class1 cls = new Class1();
        Assert.AreEqual("Jackie", cls.GetNewName("Jack"));
    }

    [TestMethod]
    public void TestMethod31()
    {
        Class1 cls = new Class1();
        Assert.AreEqual("Johnny", cls.GetNewName("John"));
    }

You should not use common private method like Verify_MethodForTesting_EchosString(string testString) containing Assert from different test methods - that's not best practice. Your test cases are not easy to understand.

Also creation of object should be done for each test method - cft = new ClassForTesting(), when tests are run in parallel, shared object may create problem.

For code coverage, you should use Tool as described here (available for VS Enterprise edition). Also some information here in this article.

Upvotes: 4

Turbofant
Turbofant

Reputation: 531

You forgot the

[TestMethod]

annotation above your last test methode.

Upvotes: 1

apomene
apomene

Reputation: 14389

You have not mark it as a test method. Try adding the corresponding attribute:

[TestMethod]
public object MethodForTesting1()
{
  ...

Upvotes: 0

Related Questions