Gau*_*uls 5 c# unit-testing moq visual-studio-2010
我想测试一个构造,该构造在其中调用两次方法以获得两个不同的值
public class stubhandler
{
public stubhandler()
{
string codetext = model.getValueByCode(int a,string b); // 1,"High" result Canada
string datatext = model.getValueByCode(int a,string b); // 10, "Slow" result Motion
}
}
Run Code Online (Sandbox Code Playgroud)
为了测试上面我使用单元测试类
[TestMethod]
public void StubHandlerConstructor_Test()
{
Mock<Model> objMock = new Mock<>(Model);
objMock.Setup(m => m.getValueByCode(It.IsAny<int>,It.IsAny<string>)).Returns("Canada");
objMock.Setup(m => m.getValueByCode(It.IsAny<int>,It.IsAny<string>)).Returns("Motion");
stubhandler classstubhandler = new stubhandler();
}
Run Code Online (Sandbox Code Playgroud)
上面的方法通过但是codetext和datatext包含我希望它们设置的相同值Motion
codetext = Canada
datatext = Motion
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现这一目标?
我试过objMock.VerifyAll()没试过?
如果使用MOQ 4,可以使用SetupSequence,否则可以使用lambda完成
使用SetupSequence非常自我解释.
使用lambdas不是太乱.重要的一点是,在声明设置时设置返回值.如果一个人刚刚使用过
mockFoo.Setup(mk => mk.Bar()).Returns(pieces[pieceIdx++]);
Run Code Online (Sandbox Code Playgroud)
设置将始终返回片段[0].通过使用lambda,延迟评估直到调用Bar().
public interface IFoo {
string Bar();
}
public class Snafu {
private IFoo _foo;
public Snafu(IFoo foo) {
_foo = foo;
}
public string GetGreeting() {
return string.Format("{0} {1}",
_foo.Bar(),
_foo.Bar());
}
}
[TestMethod]
public void UsingSequences() {
var mockFoo = new Mock<IFoo>();
mockFoo.SetupSequence(mk => mk.Bar()).Returns("Hello").Returns("World");
var snafu = new Snafu(mockFoo.Object);
Assert.AreEqual("Hello World", snafu.GetGreeting());
}
[TestMethod]
public void NotUsingSequences() {
var pieces = new[] {
"Hello",
"World"
};
var pieceIdx = 0;
var mockFoo = new Mock<IFoo>();
mockFoo.Setup(mk => mk.Bar()).Returns(()=>pieces[pieceIdx++]);
var snafu = new Snafu(mockFoo.Object);
Assert.AreEqual("Hello World", snafu.GetGreeting());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2581 次 |
| 最近记录: |