public void duplicateProduct(String ownerId, String copyOwnerId, String productId, String copyProductId, String barCode) { ValidationUtil.validateParameterNotNullAndNotEmptyString(copyProductId, COPY_PRODUCT_ID_PARAMETER_NAME); ValidationUtil.validateParameterNotNullAndNotEmptyString(copyProductId, COPY_OWNER_ID_PARAMETER_NAME); String trimCopyProductId = copyProductId.trim(); GJProduct templateProduct = gjProductRepository.requestProduct(ownerId, productId); Owner copyOwner = ownerRepository.requestOwner(copyOwnerId); GJProduct currentProduct = (GJProduct) productService.duplicateProduct(templateProduct, trimCopyProductId, copyOwner, barCode); currentProduct.setSizeDescription(templateProduct.getSizeDescription()); }用@Mock写一个测试方法
时间: 2023-12-11 08:02:39 浏览: 104
springMVC接收参数的几种注解.pdf
假设我们使用 Mockito 框架来进行测试,可以如下编写测试方法:
```java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ProductServiceTest {
@Mock
private GJProductRepository gjProductRepository;
@Mock
private OwnerRepository ownerRepository;
@Mock
private ProductService productService;
@InjectMocks
private ProductService testedService;
@Test(expected = IllegalArgumentException.class)
public void testDuplicateProductWithEmptyCopyProductId() {
// Arrange
String ownerId = "testOwnerId";
String copyOwnerId = "testCopyOwnerId";
String productId = "testProductId";
String copyProductId = "";
String barCode = "testBarCode";
// Act
testedService.duplicateProduct(ownerId, copyOwnerId, productId, copyProductId, barCode);
// Assert: expects an IllegalArgumentException to be thrown
}
// TODO: add more test cases for other parameters
}
```
在上述代码中,我们使用 `@Mock` 注解标记需要模拟的依赖对象,使用 `@InjectMocks` 注解标记被测试的服务对象。然后,我们编写了一个名为 `testDuplicateProductWithEmptyCopyProductId` 的测试方法,该方法测试当 `copyProductId` 参数为空时,是否会抛出 `IllegalArgumentException` 异常。在该测试方法中,我们首先准备好测试数据,然后调用被测试的服务方法,并期望该方法会抛出 `IllegalArgumentException` 异常。如果方法没有抛出异常,测试将会失败。
阅读全文