我有一个方法,需要5个参数.此方法用于获取一堆收集的信息并将其发送到我的服务器.
我正在为这种方法编写单元测试,但我遇到了一些麻烦.有几个参数是Lists <>类,需要做一些正确的设置.我有方法在其他单位(生产代码单位)中正确设置它们.但是,如果我打电话给那些,那么我就打破了单元测试的整个想法(只打了一个"单位").
那么......我该怎么办?我是否在我的测试项目中复制了设置这些对象的代码(在辅助方法中),或者我是否开始调用生产代码来设置这些对象?
这是一个假设的例子,试图让这个更清楚:
文件:UserDemographics.cs
class UserDemographics
{
// A bunch of user demographic here
// and values that get set as a user gets added to a group.
}
Run Code Online (Sandbox Code Playgroud)
文件:UserGroups.cs
class UserGroups
{
// A bunch of variables that change based on
// the demographics of the users put into them.
public AddUserDemographicsToGroup(UserDemographcis userDemographics)
{}
}
Run Code Online (Sandbox Code Playgroud)
文件:UserSetupEvent.cs
class UserSetupEvent
{
// An event to record the registering of a user
// Is highly dependant on UserDemographics and semi dependant on UserGroups
public SetupUserEvent(List<UserDemographics> userDemographics,
List<UserGroup> userGroups)
{}
}
Run Code Online (Sandbox Code Playgroud)
文件:Communications.cs
class Communications
{
public SendUserInfoToServer(SendingEvent sendingEvent,
List<UserDemographics> userDemographics,
List<UserGroup> userGroups,
List<UserSetupEvent> userSetupEvents)
{}
}
Run Code Online (Sandbox Code Playgroud)
所以,问题是:单元测试SendUserInfoToServer,我应该重复SetupUserEvent和AddUserDemographicsToGroup在我的测试项目,或者我应该只是叫他们帮我设置一些"真正的"参数?
听起来你的单位耦合得太紧密了(至少从快速查看你的问题来看)。让我好奇的是,例如,您的 UserGroups 采用 UserDemographics,而您的 UserSetupEvent 采用包含 UserDemographics 列表的 UserGroup 列表(再次)。是否应该List<UserGroup>已经包含在其构造函数中传递的 \xc3\x99serDemographics 或者我误解了它?
不知何故,这似乎是类模型的设计问题,这反过来又使得单元测试变得困难。困难的设置过程是一种代码味道,表明耦合度很高:)
\n