我需要使用mockito使用final方法模拟一些类.我写过这样的东西
@Test
public void test() {
B b = mock(B.class);
doReturn("bar called").when(b).bar();
assertEquals("must be \"overrided\"", "bar called", b.bar());
//bla-bla
}
class B {
public final String bar() {
return "fail";
}
}
Run Code Online (Sandbox Code Playgroud)
但它失败了.我尝试了一些"黑客",它的确有效.
@Test
public void hackTest() {
class NewB extends B {
public String barForTest() {
return bar();
}
}
NewB b = mock(NewB.class);
doReturn("bar called").when(b).barForTest();
assertEquals("must be \"overrided\"", "bar called", b.barForTest());
}
Run Code Online (Sandbox Code Playgroud)
它有效,但"闻起来".
那么,正确的方式在哪里?
谢谢.
我需要模拟一个测试场景,我在其中调用getBytes()String对象的方法,并得到UnsupportedEncodingException.
我试图使用以下代码实现:
String nonEncodedString = mock(String.class);
when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error."));
Run Code Online (Sandbox Code Playgroud)
问题是,当我运行我的测试用例时,我得到一个MockitoException,表示我无法模拟java.lang.String类.
有没有办法使用mockito模拟String对象,或者,当我调用getBytes方法时,一种方法使我的String对象抛出UnsupportedEncodingException?
以下是更多细节来说明问题:
这是我要测试的类:
public final class A {
public static String f(String str){
try {
return new String(str.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// This is the catch block that I want to exercise.
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试类(我使用的是JUnit 4和mockito):
public class TestA {
@Test(expected=UnsupportedEncodingException.class)
public void test(){
String aString = mock(String.class);
when(nonEncodedString.getBytes(anyString())).thenThrow(new UnsupportedEncodingException("Parsing error."));
A.f(aString);
}
}
Run Code Online (Sandbox Code Playgroud) 我为我的应用程序编写了自定义JsonSerializer和JsonDeserializer.现在我想为它们编写一些单元测试.
干净的测试用例应该如何?
那里有一些干净的例子吗?
(clean表示不依赖于其他框架或库)
我有一个非常简单的测试用例,它使用的是Mockito和Spring Test框架.当我做
when(pcUserService.read("1")).thenReturn(pcUser);
Run Code Online (Sandbox Code Playgroud)
我得到了这个例外.
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
at com.project.cleaner.controller.test.PcUserControllerTest.shouldGetPcUser(PcUserControllerTest.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
Run Code Online (Sandbox Code Playgroud)
我尝试过不同的方法,但继续收到此错误消息.我正在使用Spring 3.1.0.RELEASE和Mockito.请分享并指导我正确的方向.
给出一个Kotlin单例对象和一个称之为方法的乐趣
object SomeObject {
fun someFun() {}
}
fun callerFun() {
SomeObject.someFun()
}
Run Code Online (Sandbox Code Playgroud)
有没有办法模拟电话SomeObject.someFun()?
我正在尝试构建一个CloseableHttpResponse模拟对象,以便在我的一个单元测试中返回,但是它没有构造函数.我找到了这个DefaultHttpResponseFactory,但它只生成一个HttpResponse.构建CloseableHttpResponse的简单方法是什么?我是否需要调用execute()我的测试然后设置statusLine和entity?这似乎是一种奇怪的方法.
这是我试图模拟的方法:
public static CloseableHttpResponse getViaProxy(String url, String ip, int port, String username,
String password) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(ip, port),
new UsernamePasswordCredentials(username, password));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
try {
RequestConfig config = RequestConfig.custom()
.setProxy(new HttpHost(ip, port))
.build();
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(config);
LOGGER.info("executing request: " + httpGet.getRequestLine() + " via proxy ip: " + ip + " port: " + port +
" …Run Code Online (Sandbox Code Playgroud) 我正在从我正在进行的项目中删除Powermock,所以我试图仅用Mockito(mockito-core-2.2.28)重写一些现有的单一测试.
当我运行测试时,我有以下错误:
org.mockito.exceptions.base.MockitoException:
不能模拟/间谍类com.ExternalpackagePath.Externalclass
Mockito不能嘲笑/间谍,因为:
- 最后一堂课
我知道,这个问题已经被问(如何嘲弄与一的Mockito final类,调用final类与静态的Mockito方法Mock对象),但我没有找到我要找的答案.
这是我的代码的摘录:
public class MyClassToTest extends TestCase {
private MyClass myClass;
@Mock private Externalclass ext; // This class is final, I would like to mock it
@Override
protected void setUp() throws Exception {
MockitoAnnotations.initMocks(this); // <<<< The exception is thrown here
ext = Mockito.mock(Externalclass.class);
}
}
Run Code Online (Sandbox Code Playgroud)
由于文档的Mockito中提到(https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2,§Mock的unmockable),我增加了org.mockito.plugins.MockMaker文件.这是我项目的树:
我还尝试将"resources"目录放在"src"中,在一个名为"test"的子目录中,但结果仍然相同.
我认为用Mockito v2嘲笑决赛是可能的.有人知道这里缺少什么吗?
谢谢!
我无法使用Mockito 2模拟Kotlin决赛课.我还在使用Robolectric.
这是我的测试代码:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class Test {
// more mocks
@Mock
MyKotlinLoader kotlinLoader;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
}
Run Code Online (Sandbox Code Playgroud)
当我们尝试初始化setUp()方法中的模拟时,测试失败.
另外,我在我的代码中使用以下gradle依赖项:
testCompile 'org.robolectric:robolectric:3.3.2'
testCompile 'org.robolectric:shadows-multidex:3.3.2'
testCompile 'org.robolectric:shadows-support-v4:3.3.2'
testCompile("org.powermock:powermock-api-mockito2:1.7.0") {
exclude module: 'hamcrest-core'
exclude module: 'objenesis'
}
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-inline:2.8.9'
Run Code Online (Sandbox Code Playgroud)
所有其他单元测试都使用此配置传递,但是一旦我尝试模拟Kotlin类,它就会抛出以下错误:
Mockito cannot mock/spy because :
- final class
请注意我使用的是Mockito版本2,我正在使用inline依赖项,它可以自动启用模拟最终类的功能.
我为静态方法编写了一些单元测试。静态方法只接受一个参数。参数的类型是 final 类。在代码方面:
public class Utility {
public static Optional<String> getName(Customer customer) {
// method's body.
}
}
public final class Customer {
// class definition
}
Run Code Online (Sandbox Code Playgroud)
因此,对于Utility该类,我创建了一个测试类,UtilityTests在该类中我为此方法编写了测试getName。单元测试框架是TestNG,使用的模拟库是Mockito. 所以一个典型的测试具有以下结构:
public class UtilityTests {
@Test
public void getNameTest() {
// Arrange
Customer customerMock = Mockito.mock(Customer.class);
Mockito.when(...).thenReturn(...);
// Act
Optional<String> name = Utility.getName(customerMock);
// Assert
Assert.assertTrue(...);
}
}
Run Code Online (Sandbox Code Playgroud)
问题是什么 ?
虽然测试在本地成功运行,但在 IntelliJ 中,它们在 Jenkins 上失败(当我将代码推送到远程分支时,会触发构建并在最后运行单元测试)。错误消息类似于以下内容:
org.mockito.exceptions.base.MockitoException: 不能模拟/监视类 com.packagename.Customer Mockito 不能模拟/监视,因为: - 最终类 …
我正在开发一种编程游戏,玩家可以访问抽象类并扩展它以控制机器人的行为.因为它是一个编程游戏,我试图保护我的游戏基础设施,以便玩家不会混淆游戏,而不仅仅是我给他们的课程; 为此,我完成了大部分课程,final但现在我无法在单元测试中模拟它们(mockito + testNG).
所以我想知道,我该如何解决这个问题呢?有没有办法可以让这些类非最终用于测试,然后final在构建周期的后期以某种方式自动" -ize"它们(我正在使用maven,以防它与答案相关).我不想添加另一个外部库或更改我的模拟库.
如果不可能,那么第二个问题是final:让课程真正安全吗?我看到一些库可以final从字节码中删除分类器,这让我觉得final如果可以从已经编译的类中删除它可能会没用
mockito ×9
java ×8
unit-testing ×7
mocking ×5
kotlin ×2
android ×1
controller ×1
jackson ×1
maven ×1
powermock ×1
powermockito ×1
spring-test ×1
testing ×1
testng ×1