gpt4 book ai didi

asp.net-mvc - 需要帮助在我的 mvc3 项目中对我的服务层进行单元测试

转载 作者:行者123 更新时间:2023-12-02 14:51:14 25 4
gpt4 key购买 nike

我的 mvc3 项目有服务层和存储库层。

我的服务层:

public class UserService : IUserService
{
private readonly IUserRepository _userRepository;

public UserService(IUserRepository userRepository)
{
_userRepository = userRepository;
}

public ActionConfirmation<User> AddUser(User user)
{
User existUser = _userRepository.GetUserByEmail(user.Email, AccountType.Smoothie);
ActionConfirmation<User> confirmation;

if (existUser != null)
{
confirmation = new ActionConfirmation<User>()
{
WasSuccessful = false,
Message = "This Email already exists",
Value = null
};

}
else
{
int userId = _userRepository.Save(user);
user.Id = userId;

confirmation = new ActionConfirmation<User>()
{
WasSuccessful = true,
Message = "",
Value = user
};
}

return confirmation;


}

}

这是我的单元测试,不知道如何执行操作和断言。请帮助我,如果您需要其他层的代码,请告诉我。我会把它们放在这里。我想这应该足够了。

[TestFixture]
public class UserServiceTests
{
private UserService _userService;
private List<User> _users;
private Mock<IUserRepository> _mockUserRepository;

[SetUp]
public void SetUp()
{
_mockUserRepository = new Mock<IUserRepository>();
_users = new List<User>
{
new User { Id = 1, Email = "test@hotmail.com", Password = "" },
new User { Id = 1, Email = "test2@hotmail.com", Password = "123456".Hash() },
new User { Id = 2, Email = "9422722@twitter.com", Password = "" },
new User { Id = 3, Email = "john.test@test.com", Password = "12345".Hash() }
};
}

[Test]
public void AddUser_adding_a_nonexist_user_should_return_success_confirmation()
{
// Arrange
_mockUserRepository.Setup(s => s.Save(It.IsAny<User>())).Callback((User user) => _users.Add(user));
var newUser = new User { Id = 4, Email = "newuser@test.com", Password = "1234567".Hash() };

_userService = new UserService(_mockUserRepository.Object);


// Act


// Assert

}

}

最佳答案

顺便说一句,最好在编写代码之前编写测试。这将允许您设计更方便的 API,并且在编写测试时不会受到实现细节的限制。

回到你的案例。您正在使用模拟存储库,因此您不需要调用 Save 来用某些用户填充存储库。实际上你根本不需要填写mock。您应该只返回测试场景所需的值。

[Test]
public void ShouldSuccesfulltyAddNonExistingUser()
{
// Arrrange
int userId = 5;
var user = new User { Email = "newuser@test.com", Password = "1234567".Hash() };
_mockUserRepository.Setup(r => r.GetUserByEmail(user.Email, AccountType.Smoothie)).Returns(null);
_mockUserRepository.Setup(r => r.Save(user)).Returns(userId);
_userService = new UserService(_mockUserRepository.Object);

// Act
ActionConfirmation<User> confirmation = _userService.AddUser(user);

// Assert
Assert.True(confirmation.WasSuccessful);
Assert.That(confirmation.Message, Is.EqualTo(""));
Assert.That(confirmation.Value, Is.EqualTo(user));
Assert.That(confirmation.Value.Id, Is.EqualTo(userId));
}

请记住,创建新用户时不应提供用户 ID。应在用户保存到存储库后分配 ID。

关于asp.net-mvc - 需要帮助在我的 mvc3 项目中对我的服务层进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11530279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com