如何对被测方法中声明的变量的属性进行单元测试

发布于 2024-12-06 16:58:01 字数 155 浏览 0 评论 0原文

我有一个服务层方法,它接收一个对象(Dto)作为参数。

在该方法中,我新建了一个业务对象,并将 Dto 的属性值传递给业务对象的属性。然后,我将业务对象作为参数传递给存储库方法调用。

我的单元测试将如何确保在测试的服务方法中声明的业务对象在其属性中接收到正确的值?

I have a service layer method that recieves an object(Dto) as a parameter.

Within that method I new up a business object and i pass the values of the properties of the Dto to the properties of the business object. I then pass the business object as a parameter to a repository method call.

How will my unit test ensure that the business object declared in the service method under test receives the right value into its properties?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

来日方长 2024-12-13 16:58:01

您可以模拟存储库(希望您可以将其注入到服务层中)并检查传入存储库的业务对象是否具有预期的属性值。

编辑:一个例子


基础设施:

public interface IRepository
{
   void Add(BusinessObject item);
}

public sealed class ServiceLayerContext
{
   private readonly IRepository repository;

   public ServiceLayerContext(IRepository repository)
   {
       this.repository = repository;
   }

   public void ProcessDto(IDtoObject dto)
   {
       var businessObject = this.CreateBusinessObject(dto);
       this.repository.Add(businessObject);
   }

   private BusinessObject CreateBusinessObject(IDtoObject dto)
   {
   }
}

测试伪代码(因为RhinoMockі不是Moq):

   [Test]
   public void ShouldCreateBusinessOBjectWithPropertiesInitializedByDtoValues()
   {
      // ARRANGE
      // - create mock of the IRepository
      // - create dto
      // - setup expectations for the IRepository.Add() method
      //   to check whether all property values are the same like in dto   
      var repositoryMock = MockRepository.GenerateMock<IRepository>();
      var dto = new Dto() { ... };
      BusinessObject actualBusinessObject = null;
      repositoryMock.Expect(x => x.Add(null)).IgnoreArguments().WhenCalled(
        (mi) => 
        {
            actualBusinessObject = mi[0] as BusinessObject;            
        }).Repeat().Any();

      // ACT
      // - create service layer, pass in repository mock
      // - execute svc.ProcessDto(dto)     
      var serviceLayerContext = new ServiceLayerContext(repositoryMock);
      serviceLayerContext.ProcessDto(dto);

      // ASSERT
      // - check whether expectations are passed
      Assert.IsNotNull(actualBusinessObject);
      Assert.AreEqual(dto.Id, actualBusinessObject.Id);
      ...
   }

You can mock the repository (I hope that you can inject it into the service layer) and check whether the business object passed into the repository has the expected property values.

EDIT: An example


Infrastructure:

public interface IRepository
{
   void Add(BusinessObject item);
}

public sealed class ServiceLayerContext
{
   private readonly IRepository repository;

   public ServiceLayerContext(IRepository repository)
   {
       this.repository = repository;
   }

   public void ProcessDto(IDtoObject dto)
   {
       var businessObject = this.CreateBusinessObject(dto);
       this.repository.Add(businessObject);
   }

   private BusinessObject CreateBusinessObject(IDtoObject dto)
   {
   }
}

Test pseudocode (because RhinoMockі not the Moq):

   [Test]
   public void ShouldCreateBusinessOBjectWithPropertiesInitializedByDtoValues()
   {
      // ARRANGE
      // - create mock of the IRepository
      // - create dto
      // - setup expectations for the IRepository.Add() method
      //   to check whether all property values are the same like in dto   
      var repositoryMock = MockRepository.GenerateMock<IRepository>();
      var dto = new Dto() { ... };
      BusinessObject actualBusinessObject = null;
      repositoryMock.Expect(x => x.Add(null)).IgnoreArguments().WhenCalled(
        (mi) => 
        {
            actualBusinessObject = mi[0] as BusinessObject;            
        }).Repeat().Any();

      // ACT
      // - create service layer, pass in repository mock
      // - execute svc.ProcessDto(dto)     
      var serviceLayerContext = new ServiceLayerContext(repositoryMock);
      serviceLayerContext.ProcessDto(dto);

      // ASSERT
      // - check whether expectations are passed
      Assert.IsNotNull(actualBusinessObject);
      Assert.AreEqual(dto.Id, actualBusinessObject.Id);
      ...
   }
暮年慕年 2024-12-13 16:58:01

非常感谢您的帮助。
下面的示例代码使用 moq 并用 vb.net 编写,供其他可能面临类似挑战的 vb.net 程序员使用。

具体类

Public Class UserService
Implements IUserService

Private ReadOnly userRepository As IUserRepository

Public Sub New( _
   ByVal userRepository As IUserRepository)

    Me.userRepository = userRepository

End Sub

Public Sub Edit(userDto As Dtos.UserDto) Implements Core.Interfaces.Services.IUserService.Edit

    Try
        ValidateUserProperties(userDto)

        Dim user = CreateUserObject(userDto)

        userRepository.Edit(user)


    Catch ex As Exception
        Throw
    End Try

End Sub

Private Function CreateUserObject(userDto As Dtos.UserDto) As User Implements  Core.Interfaces.Services.IUserService.CreateUserObject
    Dim user = New User With {.Id = userDto.Id, _
              .UserName = userDto.UserName, _
              .UserPassword = userDto.UserPassword, _
              .Profile = New Profile With {.Id = userDto.ProfileId}}
    Return user
End Function
Sub ValidateUserProperties(userDto As Dtos.UserDto)



End Sub

测试类

<TestFixture()>
Public Class UserServiceTest

Private userRepository As Mock(Of IUserRepository)
Public serviceUnderTest As IUserService

<SetUp()>
Public Sub SetUp()

    userRepository = New Mock(Of IUserRepository)(MockBehavior.Strict)

    serviceUnderTest = New UserService(userRepository.Object)


End Sub

<Test()>
Public Sub Test_Edit()
    'Arrange
    Dim userDto As New UserDto With {.UserName = "gbrown", .UserPassword = "power", .Id = 98, .ProfileId = 1}

    Dim userObject As User = Nothing

    userRepository.Setup(Sub(x) x.Edit(It.IsAny(Of User))) _
    .Callback(Of User)(Sub(m) userObject = m)

    'Act

    serviceUnderTest.Edit(userDto)


    'Assert

    userRepository.Verify(Sub(x) x.Edit(It.IsAny(Of User)), Times.AtLeastOnce())

    Assert.NotNull(userObject)
    Assert.AreEqual(userDto.Id, userObject.Id)
    Assert.AreEqual(userDto.ProfileId, userObject.Profile.Id)
    Assert.AreEqual(userDto.UserName, userObject.UserName)
    Assert.AreEqual(userDto.UserPassword, userObject.UserPassword)
End Sub
End Class

Thanks so much for your help.
The sample code below uses moq and its written in vb.net for other vb.net programmers that might of had similar challenges.

Concrete Class

Public Class UserService
Implements IUserService

Private ReadOnly userRepository As IUserRepository

Public Sub New( _
   ByVal userRepository As IUserRepository)

    Me.userRepository = userRepository

End Sub

Public Sub Edit(userDto As Dtos.UserDto) Implements Core.Interfaces.Services.IUserService.Edit

    Try
        ValidateUserProperties(userDto)

        Dim user = CreateUserObject(userDto)

        userRepository.Edit(user)


    Catch ex As Exception
        Throw
    End Try

End Sub

Private Function CreateUserObject(userDto As Dtos.UserDto) As User Implements  Core.Interfaces.Services.IUserService.CreateUserObject
    Dim user = New User With {.Id = userDto.Id, _
              .UserName = userDto.UserName, _
              .UserPassword = userDto.UserPassword, _
              .Profile = New Profile With {.Id = userDto.ProfileId}}
    Return user
End Function
Sub ValidateUserProperties(userDto As Dtos.UserDto)



End Sub

Test Class

<TestFixture()>
Public Class UserServiceTest

Private userRepository As Mock(Of IUserRepository)
Public serviceUnderTest As IUserService

<SetUp()>
Public Sub SetUp()

    userRepository = New Mock(Of IUserRepository)(MockBehavior.Strict)

    serviceUnderTest = New UserService(userRepository.Object)


End Sub

<Test()>
Public Sub Test_Edit()
    'Arrange
    Dim userDto As New UserDto With {.UserName = "gbrown", .UserPassword = "power", .Id = 98, .ProfileId = 1}

    Dim userObject As User = Nothing

    userRepository.Setup(Sub(x) x.Edit(It.IsAny(Of User))) _
    .Callback(Of User)(Sub(m) userObject = m)

    'Act

    serviceUnderTest.Edit(userDto)


    'Assert

    userRepository.Verify(Sub(x) x.Edit(It.IsAny(Of User)), Times.AtLeastOnce())

    Assert.NotNull(userObject)
    Assert.AreEqual(userDto.Id, userObject.Id)
    Assert.AreEqual(userDto.ProfileId, userObject.Profile.Id)
    Assert.AreEqual(userDto.UserName, userObject.UserName)
    Assert.AreEqual(userDto.UserPassword, userObject.UserPassword)
End Sub
End Class
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文