犀牛模拟期待

时间:2011-06-17 20:49:15

标签: c# .net unit-testing rhino-mocks

为什么我的测试中下面的响应总是为空?

SSO.cs

 public class SSO : ISSO
    {
        const string SSO_URL = "http://localhost";
        const string SSO_PROFILE_URL = "http://localhost";

        public AuthenticateResponse Authenticate(string userName, string password)
        {
            return GetResponse(SSO_URL);
        }

        public void GetProfile(string key)
        {
            throw new NotImplementedException();
        }

        public virtual AuthenticateResponse GetResponse(string url)
        {
            return new AuthenticateResponse();
        }
    }

    public class AuthenticateResponse
    {
        public bool Expired { get; set; }
    }

SSOTest.cs

 [TestMethod()]
public void Authenticate_Expired_ReturnTrue()
{
    var target = MockRepository.GenerateStub<SSO>();
    AuthenticateResponse authResponse = new AuthenticateResponse() { Expired = true };

    target.Expect(t => t.GetResponse("")).Return(authResponse);
    target.Replay();

    var response = target.Authenticate("mflynn", "password");


    Assert.IsTrue(response.Expired);
}

1 个答案:

答案 0 :(得分:7)

您的期望不正确。您定义了一个空字符串作为GetResponse上的参数,但您传入了值SSO_URL。所以期望不满足而是返回null。

您有两种方法可以解决此问题

一种方法是在期望

上设置IgnoreArguments()
target.Expect(t => t.GetResponse("")).IgnoreArguments().Return(authResponse);

另一种方法是将SSO_URL作为参数传递给GetResponse方法,如下所示

target.Expect(t => t.GetResponse("http://localhost")).Return(authResponse);