2020年/01月/06日

首页回退

stub fake spy mock区别

Stub

public class StubUserStore : IUserStore  
{  
    public string GetUserRole(string username)  
    {  
        return "contributor";  
    }  
  
    public List<UserDetail> GetAllUsers()  
    {  
        return new List<UserDetail>()  
        {  
            new UserDetail{ Role = "administrator", Name = "admin"},  
            new UserDetail(){ Role = "contributor", Name = "User 1"}  
        };  
    }      
}  
public interface IUserStore  
{  
    string GetUserRole(string username);  
}  
  
public class UserDetail  
{  
    public string Name { get; set; }  
    public string Role { get; set; }  
}  

Fake

public class FakeUserStore : IUserStore  
{  
    public string GetUserRole(string username)  
    {  
        if (username == "admin")  
            return "administrator";  
        else  
        return "contributor";  
    }      
}   
public interface IUserStore  
{  
    string GetUserRole(string username);  
}  

Spy

Fake的高级版本,具备状态存储

public class SpyUserStore : IUserStore  
{  
    private static int Counter { get; set; }  
  
    public SpyUserStore()  
    {  
        Counter = 0;  
    }  
  
    public string GetUserRole(string username)  
    {  
  
        if (Counter >= 1)  
            throw new Exception("Function called more than once");  
  
Counter++;  
       
    if (username == "admin")  
            return "administrator";  
        else  
            return "contributor";     
     }  
}   

Mock

mockedUserStore=new Mock<IUserStore>();  
mockedUserStore.Setup(func => func.GetUserRole("admin")).Returns("administrator");  
mockedUserStore.Setup(func => func.GetUserRole("user1")).Returns("contributor");  
mockedUserStore.Setup(func => func.GetUserRole("user2")).Returns("basic");  

原文