CorryM
CorryM

Reputation: 135

How can I verify that an internal property was set with the correct value?

Here's the piece of code:

[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);
}

How can I verify in a unit test that FooId was indeed set with a NewGuid?

Upvotes: 1

Views: 120

Answers (2)

JamesR
JamesR

Reputation: 745

With Typemock Isolator you can verify that an internal property was set like this:

  [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);
  }

or you can extract the property and assert that it's a Guid:

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

Upvotes: 2

shawkyz1
shawkyz1

Reputation: 886

Seperation of concerns is needed.

I don't exactly know what you're trying to do here. But for me this looks like

Retrieving and load some data

var novel = await RetrieveNovel(novelid);
if (novel == null) return NotFound();
if (!ModelState.IsValid) return BadRequest(ModelState);

Some business logic

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

Maybe if you seperated your logic you could easily test them.

Also if you just want to test if the FooId Attributes' value changed. Then you should mock the rest. Like Loading the Novel,saving it and the other external dependancies like UriFactory.

Upvotes: 2

Related Questions