asp.net mvc 3 moq n-tier test - 对象未设置为对象的实例

时间:2012-07-17 08:55:06

标签: asp.net-mvc-3 unit-testing moq structuremap

我有以下测试经常失败,我无法解决原因:(

[TestClass]
public class UserTest
{
    private Mock<IRolodexDA> _rmock = new Mock<IRolodexDA>();
    private Mock<ICompanyDA> _cmock = new Mock<ICompanyDA>();
    private Mock<IUserSettingsDA> _umock = new Mock<IUserSettingsDA>();
    private Mock<ICLObjectContext> _clmock = new Mock<ICLObjectContext>();


    [TestInitialize]
    public void Setup()
    {
        ObjectFactory.Inject(typeof(IRolodexDA), _rmock.Object);
        ObjectFactory.Inject(typeof(ICompanyDA), _cmock.Object);
        ObjectFactory.Inject(typeof(IUserSettingsDA), _umock.Object);
        ObjectFactory.Inject(typeof(ICLObjectContext), _clmock.Object);
    }


[TestMethod]
public void Get_does_not_return_valid_user_when_not_enabled()
{

        string email_add = "theguy@totest.com";
        List<RolodexDomain> items = new List<RolodexDomain>();
        items.Add(new RolodexDomain() {rdx_contact_name = "joe blogs", rdx_auto_key = 1, email_address = email_add, cv_udf_030 = null , sdf_rdx_001 = null });


        _rmock.Setup(s => s.Get()).Returns(items.AsQueryable());

        var result2 = _rmock.Object.Get();

        var user = new CLAPortal.Service.UserService();
        var result = user.Get(email_add);

        Assert.IsNull(result);

}

在我的服务层中,我有以下代码:

public class UserService : IUserService
{
    private readonly IRolodexDA _rolodexDA = Resolver.GetConcreteInstanceOf<IRolodexDA>();
    private readonly IUserSettingsDA _userSettingsDA = Resolver.GetConcreteInstanceOf<IUserSettingsDA>();
    private readonly ICompanyDA _companyDA = Resolver.GetConcreteInstanceOf<ICompanyDA>();
    private ICLObjectContext _context = Resolver.GetConcreteInstanceOf<ICLObjectContext>();

    public UserDomain Get(string email_address)
    {
        UserDomain user = null;
        var rdx = GetRolodexForUser(email_address);

        if (rdx != null)
        {
            user = new UserDomain()
            {
                email_address = rdx.email_address,
                name = rdx.rdx_contact_name,
                password = rdx.sdf_rdx_001,
                rdx_auto_key = rdx.rdx_auto_key,
                settings = _userSettingsDA.Get().Where(x => x.rdx_auto_key == rdx.rdx_auto_key).SingleOrDefault() ?? null
            };
        }
        return user;
    }

    private RolodexDomain GetRolodexForUser(string email_address)
    {
        var result = (_rolodexDA.Get().Where(u => u.email_address.ToUpper() == email_address.ToUpper() && u.cv_udf_030.ToUpper() == "T"));

        return result.SingleOrDefault() ?? null;
    }

问题在于调用导致服务层上的GetRolodexForUser。 当我尝试检查值时,它会将对象设置为对象的实例。

现在它应该在理论上返回一个空集合?

这是我对这个类的测试中唯一一个在重构后失败的测试,但我找不到原因:(

有什么想法吗? 谢谢!

PS这是我第一次尝试拉开我的应用程序并尝试使其可测试。所以我可能有一些基本的问题,我不理解嘲弄或依赖注入。

1 个答案:

答案 0 :(得分:0)

修复是在cv udf 030中传入一个空字符串,而不是在创建我的模拟获取列表时为null。我很确定实体框架将空值转换为空字符串