相关疑难解决方法(0)

带有 Mockito 的 When 谓词中“OR”匹配器的问题

我想做这个:

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)

java hamcrest mockito

4
推荐指数
1
解决办法
1301
查看次数

什么是mockito中正在进行的存根以及我们在哪里使用它?

谁能解释一下在嘲讽中正在进行的存根及其如何帮助在Junit Testcase中编写和嘲笑方法。

junit mockito stubbing

4
推荐指数
1
解决办法
6991
查看次数

使用Mockito 2.0.7模拟lambda表达式

我想模拟我的存储库上提供的查询,如下所示:

@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表达式并知道如何解决我的问题?

java lambda junit unit-testing mockito

4
推荐指数
1
解决办法
2万
查看次数

Mockito Internals

我试图了解Mockito的内部功能.到目前为止,我很难理解代码,而且我正在寻找关于Mockito基本工作的高级调查.

Mockito @ GrepCode

我写了一些示例代码来证明我目前的理解:

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)

因此,如果有人了解内部或有一个讨论/博客文章的链接,请分享:)

testing unit-testing mocking internals mockito

3
推荐指数
1
解决办法
1843
查看次数

Mockito 2在any(Class)方法中的更改

我已经从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()但对我来说似乎不对。

java mockito

3
推荐指数
1
解决办法
995
查看次数

参数匹配器的无效使用!预计 2 个匹配者,1 个记录:

我需要验证对 的调用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)

android mockito

2
推荐指数
1
解决办法
4411
查看次数

错误:不能用返回值存根 *不同的* void 方法

存根时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)

java mockito

2
推荐指数
1
解决办法
4576
查看次数

Mockito和回调返回“参数不同!”

我正在尝试在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)

junit android junit4 mockito

2
推荐指数
1
解决办法
1066
查看次数

Mockito - 0 个预期匹配器,2 个已记录 (InvalidUseOfMatchersException)

我参考了 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)

java exception mocking mockito

2
推荐指数
1
解决办法
6830
查看次数

Mockito单步执行失败?

好吧,这很奇怪。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)

java mockito

2
推荐指数
1
解决办法
467
查看次数

在不知道方法调用参数的情况下使用嘲笑

我正在Junit测试一个类,并且不得不创建一些Mockito模拟对象。我感兴趣的代码行是

Mockito.when(emailer.sendEmail(INPUT GOES HERE)).thenReturn(true);
Run Code Online (Sandbox Code Playgroud)

emailer的sendEmail()方法有两个参数,我不确定它们是什么。是否有某种通配符可用于替换参数而不知道它们将是什么?

java junit mockito

0
推荐指数
1
解决办法
156
查看次数

ArgumentMatchers.any()与Mockito 2中的其他匹配器

与2的Mockito,应当ArgumentMarchers.any()被用来代替像更具体的匹配器ArgumentMatchers.anyString()ArgumentMatchers.anyList()例如?应该使用特定的匹配器使代码更具可读性吗?

根据经验,使用本机时OBJETS( ,intlongdouble),boolean特定的匹配器anyInt()anyLong()anyDouble()anyBoolean()是优选的。但是其他匹配器呢?有任何想法吗?谢谢。

java unit-testing mockito

0
推荐指数
1
解决办法
4317
查看次数

仅在 Intellij 调试器中检测到 Mockito 未完成的存根异常

仅当我尝试通过 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 的内部结构吗?

debugging stub intellij-idea mockito spring-boot

0
推荐指数
1
解决办法
2230
查看次数