修改了代码结构
This commit is contained in:
@ -0,0 +1,79 @@
|
||||
package com.greenorange.promotion.junit;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.greenorange.promotion.model.dto.CommonBatchRequest;
|
||||
import com.greenorange.promotion.model.entity.PromoCode;
|
||||
import com.greenorange.promotion.service.project.impl.PromoCodeServiceImpl;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PromoCodeServiceImplTest {
|
||||
|
||||
@Spy
|
||||
@InjectMocks
|
||||
private PromoCodeServiceImpl service;
|
||||
// Spy + InjectMocks:使用真实的 PromoCodeServiceImpl,但可以 stub 它的 list(...) 和 removeByIds(...)
|
||||
|
||||
/**
|
||||
* 当存在状态为“占用”的推广码时,应抛出异常并且不执行删除
|
||||
*/
|
||||
@Test
|
||||
void delBatchPromoCode_whenCodesInUse_shouldThrow() {
|
||||
// Arrange
|
||||
List<Long> ids = Arrays.asList(1L, 2L, 3L);
|
||||
CommonBatchRequest req = new CommonBatchRequest();
|
||||
req.setIds(ids);
|
||||
|
||||
// 模拟 list(...) 返回一个非空列表,表示有正在使用的推广码
|
||||
PromoCode inUse = new PromoCode();
|
||||
inUse.setId(2L);
|
||||
inUse.setPromoCodeStatus(true);
|
||||
doReturn(Collections.singletonList(inUse))
|
||||
.when(service).list(any(LambdaQueryWrapper.class));
|
||||
|
||||
// Act & Assert
|
||||
RuntimeException ex = assertThrows(RuntimeException.class,
|
||||
() -> service.delBatchPromoCode(req));
|
||||
assertTrue(ex.getMessage().contains("当前推广码正在使用中"));
|
||||
|
||||
// 验证 removeByIds(...) 从未被调用
|
||||
verify(service, never()).removeByIds(anyList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 当所有推广码都未被占用时,应正常调用 removeByIds 删除
|
||||
*/
|
||||
@Test
|
||||
void delBatchPromoCode_whenNoCodesInUse_shouldRemove() {
|
||||
// Arrange
|
||||
List<Long> ids = Arrays.asList(4L, 5L);
|
||||
CommonBatchRequest req = new CommonBatchRequest();
|
||||
req.setIds(ids);
|
||||
|
||||
// 模拟 list(...) 返回空列表,表示无任何占用的推广码
|
||||
doReturn(Collections.emptyList())
|
||||
.when(service).list(any(LambdaQueryWrapper.class));
|
||||
|
||||
// 模拟 removeByIds(...) 返回 true,表示删除成功
|
||||
doReturn(true).when(service).removeByIds(ids);
|
||||
|
||||
// Act
|
||||
service.delBatchPromoCode(req);
|
||||
|
||||
// Assert
|
||||
// 验证 removeByIds(...) 被调用一次,且参数正是传入的 ids
|
||||
verify(service, times(1)).removeByIds(ids);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user