gpt4 book ai didi

c# - 使用最小起订量验证表达式参数

转载 作者:太空狗 更新时间:2023-10-29 23:46:35 25 4
gpt4 key购买 nike

我正在尝试验证我测试的方法是否已使用特定表达式调用。我在这上面花了好几个小时,但没有得到我想要的结果。

这是被测系统

public class sut
{
private IEntityUtil _ew;
public sut(IEntityUtil ew)
{
_ew = ew;
}

public void Search()
{
Guid id = Guid.Parse("CB594050-3845-4EAF-ABC5-34840063E94F");
var res = _ew.SelectSingle<Post>(w => w.Id == id, new PersonalSiteEntities());
}

}

这是依赖

public interface IEntityUtil
{
TEntity SelectSingle<TEntity>(Expression<Func<TEntity, bool>> predicate, System.Data.Objects.ObjectContext ctx)
where TEntity : EntityObject;
List<TEntity> SelectList<TEntity>(Expression<Func<TEntity, bool>> predicate, System.Data.Objects.ObjectContext ctx)
where TEntity : EntityObject;
bool Insert<TEntity>(TEntity entity, System.Data.Objects.ObjectContext ctx)
where TEntity : EntityObject;
}

这就是我尝试测试它的方式

  public class tst
{
[TestMethod]
public void tst1()
{
var cwMock = new Mock<ConsoleApplication1.IEntityUtil>();

Guid id = Guid.Parse("CB594050-3845-4EAF-ABC5-34840063E94F");

//cwMock.Setup(x => x.SelectSingle<ConsoleApplication1.Post>(w => w.Id == id, It.IsAny<System.Data.Objects.ObjectContext>())).Returns(new ConsoleApplication1.Post()).Verifiable();


//cwMock.Setup(x => x.SelectSingle(It.IsAny<Expression<Func<ConsoleApplication1.Post, bool>>>(), It.IsAny<System.Data.Objects.ObjectContext>())).Returns(new ConsoleApplication1.Post()).Verifiable();


Expression<Func<ConsoleApplication1.Post, bool>> func = (param) => param.Id == id;

cwMock.Setup(x => x.SelectSingle<ConsoleApplication1.Post>(func, It.IsAny<System.Data.Objects.ObjectContext>())).Returns(new ConsoleApplication1.Post());

var sut = new ConsoleApplication1.sut(cwMock.Object);

sut.Search();

//cwMock.VerifyAll();

cwMock.Verify(x => x.SelectSingle(func, It.IsAny<System.Data.Objects.ObjectContext>()));
}


}

请注意第二个注释设置将使测试通过,但它不会让我验证是否已传入特定表达式。

提前致谢。

最佳答案

对(我们帮助您)有很大帮助的两件事是

  1. 为您的测试起一个有意义的名称,以便我们了解您的需求,
  2. 将您的测试分为三个区域,并用注释或空格分隔:

    • 安排,
    • 行动,
    • 断言

这使得操作的内容更加清晰。

也就是说,在我看来,您是在尝试断言在调用 sut.Search() 时调用了一次 ew.SelectSingle

我还注意到您在测试中创建了 Guid,但从未对其进行任何操作。所以,这里有一个关于你的测试的快速建议(不使用 IDE,所以你可能会发现错误):

    [Fact]
public void Verify_SelectSingle_IsCalledOnce( ){

Guid id = Guid.Parse( "CB594050-3845-4EAF-ABC5-34840063E94F" );
var cwMock = new Mock<ConsoleApplication1.IEntityUtil>( );
var post = new ConsoleApplication1.Post{ Id = id };
cwMock
.Setup( x=> x.SelectSingle<ConsoleApplication1.Post>(It.IsAny<Guid> ))
.Returns( post );
var sut = new ConsoleApplication1.sut(cwMock.Object);



sut.Search();



cwMock.Verify(
x=> x.SelectSingle( It.IsAny<ObjectContect>( o => o.Id == id )),
Times.Once);
}

关于c# - 使用最小起订量验证表达式参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15996047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com