我有以下测试方法:
@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) 我正在模拟一个用于向远程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) 我来自 python,我一直在寻找一种在 go 中编写 yess 的方法。我在 SO 上遇到了一些事情,但对于那些应该一直需要的东西来说,它们看起来都非常麻烦和冗长。
我现在正在手机上打字,如果需要的话稍后会添加代码......但是例如......
假设我有一个调用smtp.Send中间某处的函数。我怎样才能轻松测试这个功能?
假设我有另一个命中一些外部 api(需要模拟),然后获取响应并调用类似ioutil.Readall()...我如何通过这个测试函数并模拟对 api 的调用,然后传递一些假响应数据什么时候Readall被调用?
我想询问有关对具有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并且可以给我一些提示?谢谢
因此,我对代码进行了一些分解,使其更通用,也更容易让其他人理解类似的问题
这是我的主要代码:
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()代码不起作用,因此我的代码无法进一步进行......我想我的模拟由于某种原因无法正常工作。
## 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方法有多少个参数,我只想模拟它引发的情况一个例外。
执行此操作的正确语法是什么?谢谢。
我不明白为什么我们需要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) 我已经为组件 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) 我测试了一个反应组件,它应该显示旋转器、错误或获取的食谱列表。我设法测试该组件的加载以及何时成功获取数据。我遇到测试错误的问题。我使用 msw 创建了测试服务器,它具有返回错误的路由处理程序。我使用 axios 向服务器发出请求。我认为问题出在这里:axios 发出 3 个请求,直到最后一个响应 useQuery 返回 isLoading=true, isError=false。仅此后才返回 isLoading=false, isError=true。因此,在我的错误测试中, screen.debug() 显示微调器,并且 errorMessage 返回错误,因为它找不到带有文本“error”的渲染元素,该组件应该在发生错误时显示。对此我能做什么?我没有主意了。
编辑:
我是反应测试和打字稿的新手。
来自 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) 出于测试目的,我需要模拟 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:指定的令牌无效:无法读取未定义的属性“替换”