如果我在mocked objet方法上添加注释,则禁用模拟:
@Service
public class PurchaseService extends AbstractService {
@Autowired
private CheckoutService checkoutService;
@EventAnnotation(EventTypeEnum.PRC_PRODUCT)
public CheckoutResponse buy(String productId) {
return checkoutService.buy(productId);
}
}
@Service
public class CheckoutService extends AbstractService {
public CheckoutResponse buy(ExecutionContext context, String productId) {
.....
}
测试:
@Autowired
@Spy
private UserService userService;
...
@Test
public void should_buy() {
// Given
String productId = "productId";
Loyalty loyalty = new Loyalty(15, new Grade("1", "label", 10));
when(catalogClient.findPromoProductForMember(DEFAULT_TENANT, productId, userId)).thenReturn(promoProduct);
when(userService.getUserLoyalty(userId)).thenReturn(loyalty);
// When
CheckoutResponse result = purchaseService.buy(productId); // <---
// Then
assertThat(response).isNotNull();
assertThat(result).isSameAs(response);
}
如果我改变purchaseService.buy
CheckoutResponse result = checkoutService.buy
,它有效
有解决方案还是四处走动?
答案 0 :(得分:1)
不要将UserService注入您的测试中。只是嘲笑它。这是一个单元测试,而不是集成测试。你不需要从你正在测试的班级中调用任何真实的东西。
不要使用Spy注释。 声明一个@Before方法并监视其中注入的对象。 例如,
import static org.mockito.Mockito.spy;
@Autowired
private Smashy smasher;
@Before
public void preTestSetup()
{
// I love to do unnecessary work! (be sure to include this comment).
smasher = spy(smasher);
}
<强> 修改 强> 如果以下评论中的1或2为真, 我相信您可能需要模拟 Smashy 界面或执行此操作:
@Before
public void preTestSetup()
{
smasher = mock(Smashy.class); // replace the injected with a mock.
doReturn(...; // setup the mocking behavior.
}
这是;然而,只是&#34; Real Answer&#34;的变体。上方。
考虑一下:
@Mock
private Smashy mockSmashy;
@Before
public void preTestSetup()
{
MockitoAnnotations.initMocks(this);
doReturn(...; // setup the mocking behavior.
}