测试调用内部调用私有方法的公共方法的业务逻辑

时间:2016-11-11 07:30:34

标签: unit-testing asynchronous moq

我在接口中有一个方法,如下所示:

Task<bool> IsStudentAuthorizedAsync(StudentEntity studentEntity);

实施:

public async Task<bool> IsStudentAuthorizedAsync(StudentEntity studentEntity)
{
    // Check if the Student is activated for course
    var checkStudentForCourseTask = await this.CheckIfStudentIsEnabledForCourseAsync(studentEntity).ConfigureAwait(false);

    return checkStudentForCourseTask;
}

private async Task<bool> CheckIfStudentIsEnabledForCourseAsync(StudentEntity studentEntity)
{
    var result = await this.tableStorage.RetrieveAsync<StudentTableEntity>(StudentEntity.Id, StudentEntity.CourseId, this.tableName).ConfigureAwait(false);

    return result != null && result.IsActivated;
}

CheckIfStudentIsEnabledForCourseAsync是通过查询Azure表存储进行检查的私有方法。

我正在尝试单元测试IsStudentAuthorizedAsync但在初始安装调用后无法继续前进。

[TestClass]
public class AuthorizeStudentServiceBusinessLogicTests
{
    private Mock<IAuthorizeStudentServiceBusinessLogic> authorizeStudentServiceBusinessLogic;

    [TestMethod]
    public async Task IsStudentAuthorizedForServiceAsyncTest()
    {
        this.authorizeStudentServiceBusinessLogic.Setup(
                x => x.IsStudentAuthorizedAsync(It.IsAny<StudentEntity>()))
            .Returns(new Task<bool>(() => false));

        // What to do next!!!
    }
}

非常感谢任何帮助,让我开始走这条道路。 提前谢谢。

问候。

1 个答案:

答案 0 :(得分:2)

您必须模拟对存储的访问,而不是您的业务逻辑。要实现这一目标,您必须再创建一个层:

public class Storage : IStorage {
    public Task<Student> RetrieveAsync();
}

public class BusinessLogic
{
    public BusinessLogic(IStorage storage)
    {
        _storage = storage;
    }

    public async Task<bool> IsStudentAuthorizedAsync(StudentEntity studentEntity)
    {
        // Check if the Student is activated for course
        var checkStudentForCourseTask = await this.CheckIfStudentIsEnabledForCourseAsync(studentEntity).ConfigureAwait(false);

        return checkStudentForCourseTask;
    }

    private async Task<bool> CheckIfStudentIsEnabledForCourseAsync(StudentEntity studentEntity)
    {
        var result = await _storage.RetrieveAsync<StudentTableEntity>(StudentEntity.Id, StudentEntity.CourseId, this.tableName).ConfigureAwait(false);

        return result != null && result.IsActivated;
    }
}

然后,您可以模拟对存储的访问权限:

[TestMethod]
public void IsStudentAuthorizedForServiceAsyncTest()
{
    Mock<IStorage> storageMock = new Mock<IStorage>();
    storageMock.Setup(x => x.Retrieve()).Returns(new Task<Student>()); // Return whatever you need
    var target = new BusinessLogic(storageMock.Object);

    var actual = target.IsStudentAuthorizedAsync();

    // Assert
}