提取修改猪群数量逻辑

This commit is contained in:
2025-10-06 15:08:32 +08:00
parent 59b6977367
commit 91e18c432c
8 changed files with 66 additions and 54 deletions

View File

@@ -26,7 +26,7 @@ type MockDeviceRepository struct {
mock.Mock
}
// Create 模拟 DeviceRepository 的 Create 方法
// CreateTx 模拟 DeviceRepository 的 CreateTx 方法
func (m *MockDeviceRepository) Create(device *models.Device) error {
args := m.Called(device)
return args.Error(0)
@@ -169,7 +169,7 @@ func TestCreateDevice(t *testing.T) {
Properties: controller.Properties(`{"lora_address":"0x1234"}`),
},
mockRepoSetup: func(m *MockDeviceRepository) {
m.On("Create", mock.MatchedBy(func(dev *models.Device) bool {
m.On("CreateTx", mock.MatchedBy(func(dev *models.Device) bool {
// 检查 Name 字段
nameMatch := dev.Name == "主控A"
// 检查 Type 字段
@@ -215,7 +215,7 @@ func TestCreateDevice(t *testing.T) {
Properties: controller.Properties(`{"bus_id":1,"bus_address":10}`),
},
mockRepoSetup: func(m *MockDeviceRepository) {
m.On("Create", mock.Anything).Return(nil).Run(func(args mock.Arguments) {
m.On("CreateTx", mock.Anything).Return(nil).Run(func(args mock.Arguments) {
arg := args.Get(0).(*models.Device)
arg.ID = 2
arg.CreatedAt = time.Now()
@@ -259,7 +259,7 @@ func TestCreateDevice(t *testing.T) {
Type: models.DeviceTypeDevice,
},
mockRepoSetup: func(m *MockDeviceRepository) {
m.On("Create", mock.Anything).Return(errors.New("db error")).Once()
m.On("CreateTx", mock.Anything).Return(errors.New("db error")).Once()
},
expectedStatus: http.StatusOK,
expectedCode: controller.CodeInternalError,
@@ -276,9 +276,9 @@ func TestCreateDevice(t *testing.T) {
Properties: controller.Properties(`{invalid json}`),
},
mockRepoSetup: func(m *MockDeviceRepository) {
// 期望 Create 方法被调用,并返回一个模拟的数据库错误
// 期望 CreateTx 方法被调用,并返回一个模拟的数据库错误
// 这个错误模拟的是数据库层因为 Properties 字段的 JSON 格式无效而拒绝保存
m.On("Create", mock.Anything).Return(errors.New("database error: invalid json format")).Run(func(args mock.Arguments) {
m.On("CreateTx", mock.Anything).Return(errors.New("database error: invalid json format")).Run(func(args mock.Arguments) {
dev := args.Get(0).(*models.Device)
assert.Equal(t, "无效JSON设备", dev.Name)
assert.Equal(t, models.DeviceTypeDevice, dev.Type)