标签: mocking

Mockito 模拟无法正常工作

我有以下测试方法:

@RunWith(MockitoJUnitRunner.class)
public class AccountManagerTest {

    @InjectMocks
    private AccountManager accountManager = new AccountManagerImpl(null);

    @Mock
    private AuthStorage authStorage;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    /* REGISTER TESTS */

    @Test
    public void test_whenRegister_withAlreadyExistingEmail_thenDoNotRegister() throws AuthStorageException {
        String email = "foo@bar.com";
        String name = "Foo";
        String password = "123456";
        String password2 = "123456";

        doThrow(new AuthStorageException("Email already in use")).when(authStorage).registerNewUser(Matchers.any());
        assertFalse(accountManager.register(email, name, password, password2));
    }
}
Run Code Online (Sandbox Code Playgroud)

测试以下类方法:

@Override
    public Boolean register(String email, String name, String password, String password2) {
        if (password.equals(password2)) {
            try { …
Run Code Online (Sandbox Code Playgroud)

java testing junit mocking mockito

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

使用 Mockito 根据调用时间更改模拟对象行为?

我正在模拟一个用于向远程Http服务提交一些对象的接口,逻辑如下:如果提交成功,则尝试提交对象5次,然后继续下一个,否则尝试直到达到5次,如果仍然失败,则丢弃失败。

interface EmployeeEndPoint {

    Response submit(Employee employee);

}

class Response {

    String status;

    public Response(String status) {
        this.status = status;
    }
}


class SomeService {

    private EmployeeEndPoint employeeEndPoint;


    void submit(Employee employee) {

        Response response = employeeEndPoint.submit(employee);

        if(response.status=="ERROR"){
            //put this employee in a queue and then retry 5 more time if the call succeeds then skip otherwise keep trying until the 5th.
        }
    }


}

@Mock
EmployeeEndPoint employeeEndPoint;


@Test
public void shouldStopTryingSubmittingEmployeeWhenResponseReturnsSuccessValue() {
    //I want the first

    Employee employee
             = new …
Run Code Online (Sandbox Code Playgroud)

java unit-testing mocking mockito

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

在go中嘲笑。有简单的方法吗?

我来自 python,我一直在寻找一种在 go 中编写 yess 的方法。我在 SO 上遇到了一些事情,但对于那些应该一直需要的东西来说,它们看起来都非常麻烦和冗长。

我现在正在手机上打字,如果需要的话稍后会添加代码......但是例如......

假设我有一个调用smtp.Send中间某处的函数。我怎样才能轻松测试这个功能?

假设我有另一个命中一些外部 api(需要模拟),然后获取响应并调用类似ioutil.Readall()...我如何通过这个测试函数并模拟对 api 的调用,然后传递一些假响应数据什么时候Readall被调用?

testing unit-testing mocking go

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

Android单元测试:模拟BluetoothDevice并写入parcel

我想询问有关对具有BluetoothDevice变量的类进行单元测试的问题。

我的对象是一个简单的对象,其中包含一些原始变量和一个 BluetoothDevice 变量。我的对象也是可包裹的。

最终我的代码在移动设备上运行得很好,但是当我运行单元测试时出现了奇怪的错误。

我在测试类中模拟了BluetoothDevice,如下所示:

@RunWith(RobolectricTestRunner.class)
@Config(manifest=Config.NONE)
public class BluetoothDeviceTest {

    @Mock
    BluetoothDevice device1;

    @Before
    public void initMocks(){
        MockitoAnnotations.initMocks(this);

        when(device1.getAddress()).thenReturn("01:02:03:04:05:06");
        when(device1.getName()).thenReturn("device767b1");
        when(device1.getBondState()).thenReturn(BOND_NONE);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的对象以及其他原语中,我使用:

  • 我用的是out.writeParcelable(mBluetoothDevice,0);内部@Override public void writeToParcel(Parcel out, int flags)方法。

  • 我使用mBluetoothDevice = in.readParcelable(BluetoothDevice.class.getClassLoader());内部protected MyObject(Parcel in)构造函数。

测试我的对象实例的分割的单元测试失败并出现异常 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

请再次注意,当我的代码运行完全正常并且打包在我使用的移动应用程序中运行良好时。只有单元测试表现得很奇怪。

我怀疑这是因为我的模拟BluetoothDevice变量在包裹中比正常的真实实例短,并且包裹中数据字段的顺序变得混乱。

有没有人用mocked进行过单元测试BluetoothDevice并且可以给我一些提示?谢谢

java android unit-testing mocking android-bluetooth

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

Mockito When() 不起作用

因此,我对代码进行了一些分解,使其更通用,也更容易让其他人理解类似的问题

这是我的主要代码:

protected void methodA(String name) {
        Invocation.Builder requestBuilder = webTarget.request();
        requestBuilder.header(HttpHeaders.AUTHORIZATION, authent.getPassword());

            response = request.invoke();

            if (response.equals("unsuccessfull")) {
                log.warn("warning blabla: {} ({})"); 
            } else {
                log.info("info blabla {}");
            }
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

而我的测试代码如下所示:

@Test
public void testMethodA() throws Exception {            
    final String name = "testName";

    this.subject.methodA(name);

    Authent authent = Mockito.mock(Authent.class);

    when(authent.getPassword()).thenReturn("testPW");
    assertEquals(1, logger.infos.size());

}
Run Code Online (Sandbox Code Playgroud)

正如我所说,代码更复杂,我将其分解并使其更短......希望它仍然可读。

我的问题不是我的when().thenReturn()代码不起作用,因此我的代码无法进一步进行......我想我的模拟由于某种原因无法正常工作。

java unit-testing mocking mockito

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

不同参数数量的 Python 模拟补丁语法问题

## tests file
@mock.patch('profiles.models.create_stripe_charge', StripeMocks._mock_raises_stripe_error)
def my_test(self):
    #  ... stuff


## logic file
def create_stripe_charge(customer, amount_in_cents, capture=True):
    # ... stuff

## mocks file
class StripeMocks:
    def _mock_raises_stripe_error(self):
        raise stripe.error.StripeError
Run Code Online (Sandbox Code Playgroud)

运行测试时,我遇到了_mock_raises_stripe_error() takes 1 positional argument but 3 were given'错误。

我知道我正在尝试用 1-args 方法模拟 3-args 方法,但是如果我只想告诉 Python:拜托,无论我的create_stripe_charge方法有多少个参数,我只想模拟它引发的情况一个例外。

执行此操作的正确语法是什么?谢谢。

python django unit-testing mocking

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

Python 单元测试:为什么在测试中需要“mock”?

我不明白为什么我们需要mock在一些测试用例中,特别是像下面这样:

主要.py

import requests

class Blog:
    def __init__(self, name):
        self.name = name

    def posts(self):
        response = requests.get("https://jsonplaceholder.typicode.com/posts")

        return response.json()

    def __repr__(self):
        return '<Blog: {}>'.format(self.name)
Run Code Online (Sandbox Code Playgroud)

测试.py

import main

from unittest import TestCase
from unittest.mock import patch


class TestBlog(TestCase):
    @patch('main.Blog')
    def test_blog_posts(self, MockBlog):
        blog = MockBlog()

        blog.posts.return_value = [
            {
                'userId': 1,
                'id': 1,
                'title': 'Test Title,
                'body': 'Far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the Galaxy\ lies a small unregarded …
Run Code Online (Sandbox Code Playgroud)

python django unit-testing mocking

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

jest 的 axios.create.mockImplementation 返回未定义

我已经为组件 CategoryListContainer 编写了一个测试,用于通过模拟 axios 来测试 axios get 调用,如下所示:

CategoryListContainer.test.js

import React from 'react';
import { render, cleanup, waitForElement } from '@testing-library/react';
import { Provider } from 'react-redux';
import store from '../../Store';
import axios from 'axios';
import CategoryListContainer from './CategoryListContainer';

jest.mock('axios', () => ({
  create: jest.fn(),
}));

const products = {
  data: [
    {
      id: '0',
      heading: 'Shirt',
      price: '800',
    },
    {
      id: '1',
      heading: 'Polo tees',
      price: '600',
    },
  ],
};

afterEach(cleanup);
const renderComponent = () =>
  render(
    <Provider store={store()}> …
Run Code Online (Sandbox Code Playgroud)

mocking reactjs jestjs

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

使用react-query和axios测试React组件中的错误时出现问题。使用 React 测试库、Jest、msw 进行测试

我测试了一个反应组件,它应该显示旋转器、错误或获取的食谱列表。我设法测试该组件的加载以及何时成功获取数据。我遇到测试错误的问题。我使用 msw 创建了测试服务器,它具有返回错误的路由处理程序。我使用 axios 向服务器发出请求。我认为问题出在这里:axios 发出 3 个请求,直到最后一个响应 useQuery 返回 isLoading=true, isError=false。仅此后才返回 isLoading=false, isError=true。因此,在我的错误测试中, screen.debug() 显示微调器,并且 errorMessage 返回错误,因为它找不到带有文本“error”的渲染元素,该组件应该在发生错误时显示。对此我能做什么?我没有主意了。


编辑:

  • 我发现 useQuery 中有一个设置,“重试”,默认为 3 个请求。我仍然不知道如何处理测试中的组件重试请求。

我是反应测试和打字稿的新手。

来自 RecipeList.test.tsx:

import { setupServer } from 'msw/node';
import { rest } from 'msw';
import { QueryClient, QueryClientProvider, QueryCache } from 'react-query';

import RecipeList from './RecipeList';

const server = setupServer(
  rest.get(`${someUrl}`, (req, res, ctx) =>
    res(ctx.status(200), ctx.json(data))
  )
);

const queryCache = new QueryCache();
const RecipeListWithQueryClient = () => {
  const client = new QueryClient(); …
Run Code Online (Sandbox Code Playgroud)

mocking typescript reactjs react-testing-library msw

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

无法在 Jest 中模拟 jwt-decode

出于测试目的,我需要模拟 jwt-decode 函数,但我在这里找到的建议都没有帮助。使用 jwtDecode 的代码如下所示

 import jwtDecode from 'jwt-decode';
 ...
 const { exp } = jwtDecode(accessToken);
Run Code Online (Sandbox Code Playgroud)

在测试中我需要模拟这个返回exp值。我尝试按照Mock jwt-decode in Jest中的建议来模拟它

jest.mock('jwt-decode', () => () => ({ exp: 123456 }));
const { exp } = jwtDecode('123456');
Run Code Online (Sandbox Code Playgroud)

但这会返回

InvalidTokenError:指定的令牌无效:无法读取未定义的属性“替换”

testing mocking typescript ts-jest

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