我刚开始使用一种简单的方法进行单元测试,而且我被困在下面一行(特别是Web服务对象):
public string GetToken()
{
WebService ws = new WebService("https://example.com/", HttpContext.Current.Server.MapPath("~/Config/agent.txt"));
Token token = ws.GetToken(name, values, stuff);
}
起初我尝试使用一个接口来模拟HttpContext调用,但是我很难走这条路,所以我想知道我是否只能模拟Web服务?像下面的东西,但后来我不知道如何将这个Mock对象实际“注入”到getToken方法/类中。
var webServiceMock = new Mock<WebService>("http://test.example.com", "/test/file/path");
//maybe something along this syntax?
webServiceMock.Setup(it => it.CreateGetMethod(uri)).Returns(mockWebService.Object);
我正在通过您的界面解决方案,我无法弄清楚如何在没有WebService的情况下设置令牌的实现。它调用GetIssuedTokenType但在WebServiceImpl
中不存在 public class TokenImpl : IToken
{
public Token getToken(WebService ws)
{
Token token = ws.GetIssuedTokenType(
"http://example.com",
"john.doe@example.com", values,
WebService.TokenType.EX20);
return samlToken;
}
}
public class WebServiceImpl : IWebService
{
public WebService getWebService()
{
WebService ws = new WebService("https://example.com", HttpContext.Current.Server.MapPath("~/Config/agent.txt"));
return ws;
}
}
该类的较大片段供参考:
WebService ws = new WebService("https://example.com", HttpContext.Current.Server.MapPath("~/Config/agent.txt"));
ws.BasicAuthUsername = "username";
ws.BasicAuthPassword = "pass1234";
SecurityToken token = ws.GetIssuedTokenType(audience, nameId, values, type);
答案 0 :(得分:1)
interface ITokenProvider
{
string GetToken();
}
public class WebTokenProvider
{
public string GetToken
{
// your actual implementation
}
}
模拟测试:
var mock = new Mock<ITokenProvider>();
mock.Setup(m => m.GetToken()).Returns("test-token-1");