模拟存储库/功能

时间:2012-11-28 15:47:32

标签: mocking repository expression moq

我有这段代码

public ViewResult Index(String u="", String p="")
{
var q = this.repository.First(x => x.UserName == "x" && x.Password == "y");

我用Moq嘲笑这个:

repository.Setup(method => method.First(
        x => x.UserName == "x" && x.Password == "y"
         )
    ).Returns(foo);

这很好用。

现在我更改了Controllercode:

public ViewResult Index(String u="", String p="")
{
var q = this.repository.First(x => x.UserName == u && x.Password == p);

但是现在,我在q中得到null,所以我的嘲弄不起作用。 怎么了?

谢谢boqus

2 个答案:

答案 0 :(得分:0)

首先,我希望这些不是纯文本密码。

您获得q = null的原因是

x => x.UserName == "x" && x.Password == "y"

不同
x => x.UserName == u && x.Password == p

如果您对验证逻辑不感兴趣,可以匹配任何类似的输入(假设First收到的委托类型为Func<User, bool>):

repository
   .Setup(r => r.First(It.IsAny<Func<User, bool>>()))
   .Returns(foo);

否则,您可以使用回调测试谓词与测试用户匹配:

var testUser = new User { userName = "", password = "" };

repository
   .Setup(r => r.First(It.IsAny<Func<User, bool>>()))
   .Callback<Func<User, bool>>(predicate => Assert.IsTrue(predicate(testUser)))
   .Returns(foo);

您还可以将谓词存储在回调中,然后在测试方法中稍后执行断言。如果你想更彻底地测试谓词,这可能会更好。

答案 1 :(得分:0)

这是测试中的代码:

public ViewResult Index(String u="", String p="")
{
var q = userRepository.First(x => x.UserName == u && x.Password == p);

if (q==null )
{
  //view login denied
}
else
{
    //view ok
}

单元测试代码的第一个变体/无编译错误,但在测试时返回null:

var userRepository = new Mock<IUserRepository>();
var user = new User {UserName = "x", Password = "y"};

String u="x";
String p = "y";

userRepository.Setup(method => method.First(
    x => x.UserName == u && x.Password == p
    )
).Returns(user);

单元测试代码的第二个变体/编译错误:

var userRepository = new Mock<IUserRepository>();
var user = new User {UserName = "x", Password = "y"};


// I have broken the code on 2 lines, so that the problem can be seen.
Expression<Func<User, bool>> exp =  It.IsAny<Func<User, bool>>();  //here compile error

userRepository.Setup( r => r.First( exp ) ).Returns(user);  //no compile error