我想做这个:
when(myObject.getEntity(1l,usr.getUserName()).thenReturn(null);
when(myObject.getEntity(1l,Constants.ADMIN)).thenReturn(null);
Run Code Online (Sandbox Code Playgroud)
与匹配器合二为一。所以,我有这个代码:
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import static org.mockito.AdditionalMatchers.*;
[...]
User usr = mock(usr);
[...]
when(myObject.getEntity(
eq(1l),
or(eq(usr.getUserName()),eq(Constants.ADMIN))
)
).thenReturn(null);
Run Code Online (Sandbox Code Playgroud)
但是当我使用 Or 匹配器时,JUnit 失败了:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded.
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class. …Run Code Online (Sandbox Code Playgroud) 谁能解释一下在嘲讽中正在进行的存根及其如何帮助在Junit Testcase中编写和嘲笑方法。
我想模拟我的存储库上提供的查询,如下所示:
@Test
public void GetByEmailSuccessful() {
// setup mocks
Mockito.when(this.personRepo.findAll()
.stream()
.filter(p -> (p.getEmail().equals(Mockito.any(String.class))))
.findFirst()
.get())
.thenReturn(this.personOut);
Mockito.when(this.communityUserRepo.findOne(this.communityUserId))
.thenReturn(this.communityUserOut);
...
Run Code Online (Sandbox Code Playgroud)
我的@Before方法看起来像这样:
@Before
public void initializeMocks() throws Exception {
// prepare test data.
this.PrepareTestData();
// init mocked repos.
this.personRepo = Mockito.mock(IPersonRepository.class);
this.communityUserRepo = Mockito.mock(ICommunityUserRepository.class);
this.userProfileRepo = Mockito.mock(IUserProfileRepository.class);
}
Run Code Online (Sandbox Code Playgroud)
可悲的是,当我运行测试时,我收到错误:
java.util.NoSuchElementException:没有值存在
当我双击错误时,它指向.get()第一个lambda 的方法.
有没有人成功嘲笑过一个lambda表达式并知道如何解决我的问题?
我试图了解Mockito的内部功能.到目前为止,我很难理解代码,而且我正在寻找关于Mockito基本工作的高级调查.
我写了一些示例代码来证明我目前的理解:
class C {
String s;
public void getS() { return s; }
// ...
}
C cm = mock( C.class);
when( cm.method() ).thenReturn( "string value");
Run Code Online (Sandbox Code Playgroud)
据我所知,'mock'方法只能看到cm.getS()的返回值.怎么知道方法的名称是什么(为了存根)?另外,它如何知道传递给方法的参数?
mockito API方法调用内部对象的方法:
// org.mockito.Mockito
public static <T> OngoingStubbing<T> when(T methodCall) {
return MOCKITO_CORE.when(methodCall);
}
Run Code Online (Sandbox Code Playgroud)
我已经将方法调用跟踪到几个不同的抽象,类和对象,但代码是如此分离,以至于很难理解这种方式.
// org.mockito.internal.MockitoCore
public <T> OngoingStubbing<T> when(T methodCall) {
mockingProgress.stubbingStarted();
return (OngoingStubbing) stub();
}
Run Code Online (Sandbox Code Playgroud)
因此,如果有人了解内部或有一个讨论/博客文章的链接,请分享:)
我已经从1.9版更新到Mockito 2.1。
现在我的一些测试失败了。方法似乎有所变化any(Bla.class)。在此测试还不错之前:
when(criteriaBuilder.greaterThanOrEqualTo(any(Expression.class),
any(Comparable.class)))
.thenReturn(predicate);
Run Code Online (Sandbox Code Playgroud)
现在表达式any(Expression.class)为空。
我是否需要使用另一种方法使其再次正常工作?我可以使用它,(Expression)any()但对我来说似乎不对。
我需要验证对 的调用handler.sendMessage(msg)。
代码:
//This bundleImportStorage will send message to UI handler by passing message object
bundleImporter.bundleImportFromStorage(intent);
//In this line I am getting error
when(uiHandler.sendMessage(any(Message.class))).thenReturn(true);
Run Code Online (Sandbox Code Playgroud)
异常详情:
//This bundleImportStorage will send message to UI handler by passing message object
bundleImporter.bundleImportFromStorage(intent);
//In this line I am getting error
when(uiHandler.sendMessage(any(Message.class))).thenReturn(true);
Run Code Online (Sandbox Code Playgroud) 存根时ClassOne.methodOne,我收到以下关于存根具有返回值的 void 方法的错误消息,即使ClassOne.methodOne它不是 void。该错误似乎与ClassTwo.methodTwo,即使我存根ClassOne.methodOne.
org.mockito.exceptions.base.MockitoException:
`'methodTwo'` is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. The method you are trying to stub is *overloaded*. Make sure you are calling
the right overloaded version.
2. Somewhere in your …Run Code Online (Sandbox Code Playgroud) 我正在尝试在Android上使用Mockito。我想将其与一些回调一起使用。这是我的测试:
public class LoginPresenterTest {
private User mUser = new User();
@Mock
private UsersRepository mUsersRepository;
@Mock
private LoginContract.View mLoginView;
/**
* {@link ArgumentCaptor} is a powerful Mockito API to capture argument values and use them to
* perform further actions or assertions on them.
*/
@Captor
private ArgumentCaptor<LoginUserCallback> mLoadLoginUserCallbackCaptor;
private LoginPresenter mLoginPresenter;
@Before
public void setupNotesPresenter() {
// Mockito has a very convenient way to inject mocks by using the @Mock annotation. To
// inject the mocks in the test …Run Code Online (Sandbox Code Playgroud) 我参考了 Stackoverflow 上的所有可用资源来进行类似查询。但我不确定这个测试的问题是什么:
它抛出以下异常。
[main] ERROR com.example.dao.spring.TransactionDAOSpring - org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!0 matchers expected, 2 recorded.
Run Code Online (Sandbox Code Playgroud)
以下是代码:
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyMapOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import com.example.dto.DisplayTwo;
import com.example.dto.DisplayOne;
import com.example.dto.DisplayThree;
public class TransactionDAOSpringTest {
TransactionDAOSpring transactionDAOSpring;
@Mock
DataSource dataSource;
@Mock
JdbcTemplate jdbcTemplate;
@Mock
SimpleJdbcCall …Run Code Online (Sandbox Code Playgroud) 好吧,这很奇怪。Mockito,Java,在 Windows 上。
when(mongoTemplate.findAndModify(any(Query.class), any(Update.class), any(FindAndModifyOptions.class), eq(Task.class)))
.thenReturn(t1)
.thenReturn(t2);
Run Code Online (Sandbox Code Playgroud)
现在,如果我在调试模式下运行它,它就可以正常工作。但是,如果我在时间上设置断点,并且单步执行,则会失败。
IntelliJ 中的错误是
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Task cannot be returned by toString()
toString() should return String
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies …Run Code Online (Sandbox Code Playgroud) 我正在Junit测试一个类,并且不得不创建一些Mockito模拟对象。我感兴趣的代码行是
Mockito.when(emailer.sendEmail(INPUT GOES HERE)).thenReturn(true);
Run Code Online (Sandbox Code Playgroud)
emailer的sendEmail()方法有两个参数,我不确定它们是什么。是否有某种通配符可用于替换参数而不知道它们将是什么?
与2的Mockito,应当ArgumentMarchers.any()被用来代替像更具体的匹配器ArgumentMatchers.anyString()或ArgumentMatchers.anyList()例如?应该使用特定的匹配器使代码更具可读性吗?
根据经验,使用本机时OBJETS( ,int,long,double),boolean特定的匹配器anyInt(),anyLong(),anyDouble()或anyBoolean()是优选的。但是其他匹配器呢?有任何想法吗?谢谢。
仅当我尝试通过 IntelliJ 调试器调试测试时才会出现此问题。当我只是简单地运行测试时,这种情况不会发生。
CustomerChoiceRepository 是一个普通的 Spring Boot JPA 存储库,此处使用@Mock.
当此行在调试器中执行时,我在变量的监视部分中收到以下错误:
整个错误信息是:
Method threw 'org.mockito.exceptions.misusing.UnfinishedStubbingException' exception. Cannot evaluate com.item.repository.jpa.CustomerChoiceRepository$MockitoMock$1318657964.toString()
Run Code Online (Sandbox Code Playgroud)
同样,这仅在 IntelliJ 调试器中检测到,因此仅当我调试它时测试才会失败。
所以我的问题是:这里发生了什么?
这是一个错误吗?这是我无法理解的事情,因为我不太了解 Mockito 的内部结构吗?