我有一个 maven 项目,其中有一个名为 - BookingServiceTest.java 的类,我尝试导入 org.mockito.InjectMocks org.mockito.Mock org_mockito_Mockito 和 org_mockito_MockitoAnnotations。但我收到错误 - “无法解析导入 org_mockito”
谁能建议我们如何解决这个问题?
使用的 jar:mockito-all-1.9.5.jar 添加到我的本地 Maven 存储库中。
我正在尝试实现这个 JUnit 代码:
private BinlistsService binlistsService = Mockito.mock(BinlistsService.class);
@Mock
Optional<BinLists> binList = null;
@BeforeEach
public void beforeEachTest() throws IOException {
BinLists binLists = new BinLists();
binLists.setId(1);
....
binList = Optional.of(binLists);
}
@Test
public void testBinCountryCheckFilterImpl() {
when(binlistsService.findByName(anyString())).thenReturn(binList);
}
Run Code Online (Sandbox Code Playgroud)
但我得到这个错误堆栈:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class java.util.Optional
Mockito cannot mock/spy because :
- final class
at org.data
Run Code Online (Sandbox Code Playgroud)
你知道我该如何解决这个问题吗?
Mockito继续拦截我在DAO中创建的函数并随机返回0.我希望函数能够实际运行.我在哪里可以配置这个mockito野兽单独留下功能?
调试器跳到这里而不是进入我的spring dao:
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)
throws Throwable {
if (objectMethodsGuru.isEqualsMethod(method)) {
return proxy == args[0];
} else if (objectMethodsGuru.isHashCodeMethod(method)) {
return hashCodeForMock(proxy);
}
MockitoMethodProxy mockitoMethodProxy = createMockitoMethodProxy(methodProxy);
cglibHacker.setMockitoNamingPolicy(mockitoMethodProxy);
MockitoMethod mockitoMethod = createMockitoMethod(method);
FilteredCGLIBProxyRealMethod realMethod = new FilteredCGLIBProxyRealMethod(mockitoMethodProxy);
Invocation invocation = new Invocation(proxy, mockitoMethod, args, SequenceNumber.next(), realMethod);
return handler.handle(invocation);
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试测试这种方法。
@Override
public JSON connectResource() throws IOException {
//get the location and credentials for the certificates
System.setProperty("javax.net.ssl.trustStore", "C:/Program Files/Java/jdk1.7.0_40/jre/lib/security/cacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
HttpRequest httpRequest = new HttpGet(url);
System.out.println("hello");
httpRequest.addHeader("Accept", "application/json");
HttpResponse response = httpClient.execute((HttpUriRequest) httpRequest);
System.out.println("hello1");
HttpEntity httpEntity = response.getEntity();
String data = this.getData(httpEntity);
return JSONSerializer.toJSON(data.toString());
}
Run Code Online (Sandbox Code Playgroud)
我的设置方法是:
@Before
public void setUp() throws Exception{
mockHttpClient = mock(DefaultHttpClient.class);
mockHttpRequest = mock(HttpUriRequest.class);
mockHttpResponse = mock(BasicHttpResponse.class);
mockHttpEntity = mock(HttpEntity.class);
mockInputStream = mock(InputStream.class);
mockInputStreamReader = mock(InputStreamReader.class);
mockBufferedReader = mock(BufferedReader.class);
mockHttpGet = mock(HttpGet.class);
mockHttpRequestBase = mock(HttpRequestBase.class); …Run Code Online (Sandbox Code Playgroud) 我有一个Spring Validator:
@Component
public class AddClientAccountValidator implements Validator {
@Autowired
private ValidatorUtils validatorUtils;
@Override
public boolean supports(Class<?> clazz) {
return UserDto.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
UserDto user = (UserDto) target;
validatorUtils.setParam(errors, user);
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "username.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword",
"confirmPassword.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "personalId", "personalId.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "city", "city.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "address.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "phone.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "contribution", "contribution.required");
validatorUtils.validateAddClientAccount();
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的Validator中有注入ValidatorUtils类:
@Component
class ValidatorUtils {
@Autowired
private …Run Code Online (Sandbox Code Playgroud) 我正在尝试对使用java.time.LocalDateTime. 我能够让模拟工作,但是当我增加时间(分钟或天)时,我最终会得到一个null值。
@RunWith(PowerMockRunner.class)
@PrepareForTest({ LocalDateTime.class })
public class LocalDateTimeMockTest
{
@Test
public void shouldCorrectlyCalculateTimeout()
{
// arrange
PowerMockito.mockStatic(LocalDateTime.class);
LocalDateTime fixedPointInTime = LocalDateTime.of(2017, 9, 11, 21, 28, 47);
BDDMockito.given(LocalDateTime.now()).willReturn(fixedPointInTime);
// act
LocalDateTime fixedTomorrow = LocalDateTime.now().plusDays(1); //shouldn't this have a NPE?
// assert
Assert.assertTrue(LocalDateTime.now() == fixedPointInTime); //Edit - both are Null
Assert.assertNotNull(fixedTomorrow); //Test fails here
Assert.assertEquals(12, fixedTomorrow.getDayOfMonth());
}
}
Run Code Online (Sandbox Code Playgroud)
我明白(我想我明白)这LocalDateTime是不可变的,我认为我应该得到一个新实例而不是null值。
原来是.of方法给了我一个null价值。为什么?
我正在为 Spring Boot 项目中的服务类编写单元测试。当我自动装配正在测试的类时,测试可以正确运行,而当我使用 @MockBean 而不是 @Autowire 时,测试会失败。
@SpringBootTest
class SignupServiceTest {
@Autowired SignupService signupService;
@MockBean DSService dsService;
@MockBean SignupHelper signupHelper;
@MockBean SessionHelper sessionHelper;
@MockBean CommonService commonService;
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决差异以及 @MockBean 失败的原因吗?还有一种方法可以在mockito中模拟自动装配类(当前类)的方法。
在我的 Java 代码中,我想用 Mockito 模拟一个返回布尔值的方法。事实上,它涉及一个计算停车价格的停车应用程序。在我使用 Junit5 和 Mockito 进行的测试中,我模拟了一个方法,该方法返回一个布尔值,如果该布尔值为真,则通过减少来计算价格。但我的模拟不起作用,我不知道为什么......
when(ticketDao.isRegularCustomer(any(String.class))).thenReturn(true);
Run Code Online (Sandbox Code Playgroud)
我希望这个模拟可以通过减少来计算价格。感谢您的帮助,这是我的代码。
@ExtendWith(MockitoExtension.class)
public class FareCalculatorServiceTest {
private static FareCalculatorService fareCalculatorService;
private Ticket ticket;
@Mock
private static TicketDao ticketDao;
@BeforeAll
private static void setUp() {
fareCalculatorService = new FareCalculatorService();
}
@BeforeEach
private void setUpPerTest() {
ticket = new Ticket();
//when(ticketDao.isRegularCustomer(any())).thenReturn(false);
}
@Test
public void feature2CalculateFareBikeWith5PerCentReduceIfRegularCustomer(){
Date inTime = new Date();
inTime.setTime( System.currentTimeMillis() - (45 * 60 * 1000) );//45MIN IN PARKING
Date outTime = new Date();
ParkingSpot parkingSpot = new ParkingSpot(1, …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Mockito 创建一个测试,但是我收到了 NullPointerException。
以下是会话 bean:
package edu.city.set.eia.citypress.beans;
import edu.city.set.eia.citypress.model.RegisUser;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@Stateless
public class RegisUserFacade extends AbstractFacade<RegisUser> implements RegisUserFacadeLocal {
@PersistenceContext(unitName = "citypress_PU")
private EntityManager em;
@Override
public EntityManager getEntityManager() {
return em;
}
public void setEntityManager(EntityManager em) {
this.em = em;
}
public RegisUserFacade() {
super(RegisUser.class);
}
@Override
public RegisUser findByUsername(String username) {
Query query = this.getEntityManager().createQuery("select r from RegisUser r where username=:username");
query.setParameter("username", username);
RegisUser regisuser;
try {
regisuser = (RegisUser) …Run Code Online (Sandbox Code Playgroud) 我需要创建一个List<File> files,以便它包含 3 个虚拟文件。我怎么做?
我需要它进行单元测试。
我做了
private File file1 = mock(File.class);
private File file2 = mock(File.class);
private File file3 = mock(File.class);
List<File> files = Lists.newArrayList(file1, file2, file3);
Run Code Online (Sandbox Code Playgroud)
但我认为这一切都是可能的。
在JVM中,我想改变Object类的toString方法的行为getClass().getName();而不是返回getClass().getName() + "@" + Integer.toHexString(hashCode());
我尝试过Javassist的Hotswapper,但它需要在启动tomcat服务器时分配调试端口.有没有其他方法可以更改JVM中Object类的toString()的功能?
我的用例:我的JVM中的一些对象没有toString()实现.因此,采用Object.class中的基本实现,这将不是唯一的(因为哈希码).我有一个记录和测试环境,其中值必须是唯一的,然后才能自动比较它们.
mockito ×11
java ×8
junit ×5
junit5 ×2
spring ×2
datetime ×1
dummy-data ×1
http ×1
httpclient ×1
java-time ×1
javassist ×1
list ×1
mocking ×1
powermock ×1
powermockito ×1
proxy ×1
spring-boot ×1
spring-test ×1
testing ×1
tomcat ×1
unit-testing ×1