CrazyCoder
CrazyCoder

Reputation: 2378

Tests passed but code coverage is 0%

I am still learning to use MSTest and Moq for automated unit testing in my application. I have successfully mocked the code and run it. It is showing that the tests are passed , but the code coverage is 0%. This is my code below.What needs to be changed so that code coverage becomes 100%.

I know this question has been asked a couple of times before, but nothing seems to help me.So can anyone suggest me what am I doing wrong.

Any help is highly appreciated.Thanks.

PS: I'm using Sonarcube for knowing the code coverage.

using Moq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;

namespace MyNameSpace
{
    [TestClass]
    public class ApplicationTest
    {
        readonly Helper moqHelper = new Helper();
        [TestMethod()]
        public void GetDataFromDataBaseMoq()
        {
            Task<bool> returnValue;
            Mock<Application> mockType = new Mock<Application>();
            mockType.CallBase = true;
            mockType.Setup(x => x.GetDataFromDataBase()).Returns(returnValue = moqHelper.GetDataFromDataBaseMoq());
            if (returnValue.Result)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.Fail();
            }
        }
    }

    [ExcludeFromCodeCoverage]
    class Helper
    {
        internal async Task<bool> GetDataFromDataBaseMoq()
        {
            bool returnValue = true;
            return returnValue;
        }
    }
    public class Application : IApplication
    {
        public virtual async Task<bool> GetDataFromDataBase()
        {
            //if data retrive successfull, return true, else false
            return true;
        }
    }
    public interface IApplication
    {
        Task<bool> GetDataFromDataBase();
    }
}

Upvotes: 0

Views: 3914

Answers (1)

CodeCaster
CodeCaster

Reputation: 151588

You're not testing your application code, you're testing your mock. You could've seen this by setting a breakpoint in Application.GetDataFromDataBase() and debugging your test; you'd see it won't be hit.

You need to only mock dependencies, if any. So rewrite your test to actually call into your code:

[TestMethod]
public async Task GetDataFromDataBase_Returns_True()
{
    // Arrange
    IApplication classUnderTest = new Application();

    // Act
    var result = await classUnderTest.GetDataFromDataBase();

    // Assert
    Assert.IsTrue(result);
}

And you'll see the need for all the mocks and helpers goes away.

Upvotes: 5

Related Questions