Unit Test Method Always Returns A Null Value

I’m trying to unit test a method using MSTest and MOQ but it always fails. The following is a method in the BL layer which I’m trying to unit test. It calls to a method in the DAL layer and returns a value of type double if the id used to call the said method is authorized.

public class BLService:IBLService
  IDAL dal = IDAL();
  public double? GetTestScore(int Id ){
     if(dal.IsAuthorized(Id)){      
        return dal.GetTestScoreFromDB(Id);
     }else{
        return null;
     }
}

I thought that I could setup my mock object like the following and return any number I wanted.

mockObj.Setup(x=>x.GetTestScoreFromDB(It.IsAny<int>())).Returns(80.00);

Then in the body of my unit test method I can do the following:

mockDal = new Mock<IDAL>();
int id = 1234;

double? expectedResult = 80.0;
service = new service();
service.GetTestScore(id);
double actualResult = mockDal.GetTestScoreFromDB(id);
Assert.AreEqual(expectedResult,actualResult)

I was expecting actualResult to be 80.00 when running the unit test but it’s always null unless I pass the right id to the method GetTestScore. This because of the if statement in GetTestScore which checks if the supplied id is authorized. I thought that the Setup() method can be forced to return anything you want but that doesn’t seem to be the case. Am I missing something?

Well this sets up mockObj.

mockDal != mockObj.

Hi Thanks for your reply. The issue in the code that you pointed out was just a copy paste error when I was writing this question. I copied the line for the mock setup from a different layer. My actual code in the BL layer is fine, mockObj is mockDal is in the BL layer. The issue is I’m always getting null because of the IsAuthorized check.

Yeah, you need to mock IsAuthorized too.
Also, you should mark IDAL dal as internal so you can assign it (unless you have another way you are setting it in your test on the BLService). Then add [assembly:InternalsVisibleTo("MyTests")] to your Service’s project AssemblyInfo.cs

Inside BLService:

internal IDAL dal = IDAL();

In your test

// setup IsAuthorized and GetTestScoreFromDB
service.dal = mockDal.Object;
var result = service.GetTestScore(id);
Assert.AreEqual(expectedResult, result);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.