How to do unit test this business logic?

I have a method that takes an object and stores it in a database. But, before I save the object, I do the following ...

(psuedo code)

if (IsAuthenticated)
{
   foo.UserId = AuthenticatedUser.Id;
}
else
{
   foo.AnonEmail = "Jon@World-Domination";
   foo.AnonName = "Jon Skeet";
}

try
{
    _fooService.Save(foo);
}
catch
{
    // Some view, with error stuff now added to 
    return View(...); ViewData.ModelState.
}

// all good, redirect to the proper next view.
return RedirectToAction(...);

This code works fine, but I'm not sure how to write two unit tests for success. a) The user is authenticated with reliable data b) The user is not authenticated with reliable data.

The reason I'm not sure what to do is because both scripts return the same RedirectToAction (..) view object. Therefore, I can successfully test this. But it doesn’t tell me if the object contains the stored user ID or anonymous information. I like the first unit test to say

  • authenticate user
  • call method
  • test, RedirectToActionView
  • , foo, , moq'd.

?

Update

, fooService. Dependency Injection Moq, - , Moq? , DI , ???

+3
6

_fooService , . , , , , _fooService, , . .

_fooService? "" ( , ), . , _fooService ( - . , )

+3

_fooService.Save(foo) foo.

+1

, , .

- .

  • /

(IUserDecoratorService),

userService.UpdateUserInformation(foo);

try
{
    _fooService.Save(foo);
}
catch
{
    // Some view, with error stuff now added to 
    return View(...); ViewData.ModelState.
}

// all good, redirect to the proper next view.
return RedirectToAction(...);

, 2 2- , .

:

[Test]
public void ShouldDecorateWithUserIdForAuthenticatedUser()
{
    {setup authenticated user}
    :
    service.UpdateUserInformation(foo);

    Assert.AreEqual(expectedId, foo.UserId);
    Assert.IsNull(foo.AnonEmail);
    Assert.IsNull(foo.AnonEName);

}

[Test]
public void ShouldSpoofTheAllKnowingSkeetIfAnonymousUser()
{
    {setup anonymous user}
    :
    service.UpdateUserInformation(foo);

    Assert.AreEqual(UnassignedId, foo.UserId);
    Assert.AreEqual("Jon@World-Domination", foo.AnonEmail);
    Assert.AreEqual("Jon Skeet", foo.AnonName);

}
+1

. unit test , foo.AnonEmail UserId?

. ( ), , , , .

0

foo ? , . ? , , , Reflection ( , asp.net, )

0

DI, fooservice , ;

( Moq)

[TestMethod]
public void Jon_Skeet_Is_Saved_If_User_Not_Authenticated()
{
  bool jonWasSaved = false;
  var mockFooService = new Mock<IFooService>();
  mockFooService
       .Expect(x => x.Save(It.Is<Foo>(foo => foo.AnonName == "Jon Skeet")))
       .Callback(() => jonWasSaved = true;);

  FooManager instance = new FooManager(mockFooService.Object);
  Foo testFoo = new Foo();
  testFoo.UserId = 1; // this is not the authenticated id

  instance.baa(foo);

  Assert.IsTrue(jonWasSaved);
}

, AuthetnicatedUser.Id

0

Source: https://habr.com/ru/post/1706039/


All Articles