这是一段代码:

[HttpPost(UriFactory.FOO_ROUTE)]

public async Task<ActionResult> AddFooAsync([FromRoute]string novelid, [FromBody]AddFoo command)
{
    var novel = await RetrieveNovel(novelid);
    if (novel == null) return NotFound();
    if (!ModelState.IsValid) return BadRequest(ModelState);

    command.FooId = Guid.NewGuid();
    novel.AddFoo(command);
    await _store.SaveAsync(novel);

    return Created(UriFactory.GetFooRoute(novel.Novel.NovelId, command.FooId), command);
}


如何在单元测试中验证FooId确实是用NewGuid设置的?

最佳答案

使用Typemock Isolator,您可以验证是否设置了如下内部属性:

  [TestMethod, Isolated]
  public void Test1
  {
      var testFoo = Isolate.Fake.Dependencies<AddFoo>();
      var newGuid = new Guid();
      testFoo.FooId = Guid.NewGuid()
      Isolate.Verify.NonPublic.Property.WasCalledSet(testFoo, "FooId").WithArgument(newGuid);
  }


或者您可以提取属性并断言它是Guid:

  [TestMethod, Isolated]
  public void Test2
  {
      var testFoo = Isolate.Fake.Dependencies<AddFoo>();
      var fooID = Isolate.Invoke.Method(testFoo , "getFooID");
      Assert.IsTrue(fooID is Guid);
  }

07-26 06:31