标签: mockito

使用Mockito在其中调用new()调用的测试类

我有一个遗留类,其中包含一个new()调用来实例化LoginContext():

public class TestedClass {
  public LoginContext login(String user, String password) {
    LoginContext lc = new LoginContext("login", callbackHandler);
  }
}
Run Code Online (Sandbox Code Playgroud)

我想使用Mockito测试这个类来模拟LoginContext,因为它要求在实例化之前设置JAAS安全性东西,但是我不知道如何在不更改login()方法来外化LoginContext的情况下这样做.是否可以使用Mockito来模拟LoginContext类?

java junit unit-testing mockito

57
推荐指数
4
解决办法
12万
查看次数

如何在Log中模拟方法e

这里Utils.java是我要测试的类,以下是在UtilsTest类中调用的方法.即使我正在嘲笑Log.e方法,如下所示

 @Before
  public void setUp() {
  when(Log.e(any(String.class),any(String.class))).thenReturn(any(Integer.class));
            utils = spy(new Utils());
  }
Run Code Online (Sandbox Code Playgroud)

我收到以下异常

java.lang.RuntimeException: Method e in android.util.Log not mocked. See http://g.co/androidstudio/not-mocked for details.
    at android.util.Log.e(Log.java)
    at com.xxx.demo.utils.UtilsTest.setUp(UtilsTest.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Run Code Online (Sandbox Code Playgroud)

junit android mockito

57
推荐指数
10
解决办法
3万
查看次数

使用PowerMock和Mockito模拟Logger和LoggerFactory

我有以下Logger我想模拟,但验证日志条目被调用,而不是内容.

private static Logger logger = 
        LoggerFactory.getLogger(GoodbyeController.class);
Run Code Online (Sandbox Code Playgroud)

我想模拟用于LoggerFactory.getLogger()的任何类,但我无法找到如何做到这一点.这是我到目前为止所得到的:

@Before
public void performBeforeEachTest() {
    PowerMockito.mockStatic(LoggerFactory.class);
    when(LoggerFactory.getLogger(GoodbyeController.class)).
        thenReturn(loggerMock);

    when(loggerMock.isDebugEnabled()).thenReturn(true);
    doNothing().when(loggerMock).error(any(String.class));

    ...
}
Run Code Online (Sandbox Code Playgroud)

我想知道:

  1. 我可以模拟静态LoggerFactory.getLogger()以适用于任何类吗?
  2. 我只能似乎运行when(loggerMock.isDebugEnabled()).thenReturn(true);@Before,因此我似乎无法改变每个方法的特点.有没有解决的办法?

编辑发现:

我以为我已经尝试了这个并且它没有用:

 when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
Run Code Online (Sandbox Code Playgroud)

但是,谢谢你,因为它确实有效.

但是我尝试了无数的变化:

when(loggerMock.isDebugEnabled()).thenReturn(true);
Run Code Online (Sandbox Code Playgroud)

我不能让loggerMock改变它的行为,@Before但这只发生在Coburtura上.使用Clover,覆盖率显示为100%,但仍然存在问题.

我有这个简单的课程:

public ExampleService{
    private static final Logger logger =
            LoggerFactory.getLogger(ExampleService.class);

    public String getMessage() {        
    if(logger.isDebugEnabled()){
        logger.debug("isDebugEnabled");
        logger.debug("isDebugEnabled");
    }
    return "Hello world!";
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class ExampleServiceTests {

    @Mock
    private Logger loggerMock;
    private ExampleServiceservice = new ExampleService();

    @Before
    public …
Run Code Online (Sandbox Code Playgroud)

java junit slf4j mockito powermock

56
推荐指数
3
解决办法
9万
查看次数

在mockito中使用doThrow()doAnswer()doNothing()和doReturn()的用法

我正在学习mockito,我从链接中了解了上述功能的基本用法.

但我想知道它是否可以用于任何其他情况?

java mockito

55
推荐指数
4
解决办法
17万
查看次数

mockito返回值基于参数的属性

通常在使用mockito时我会做类似的事情

Mockito.when(myObject.myFunction(myParameter)).thenReturn(myResult);
Run Code Online (Sandbox Code Playgroud)

是否有可能做一些事情

myParameter.setProperty("value");
Mockito.when(myObject.myFunction(myParameter)).thenReturn("myResult");

myParameter.setProperty("otherValue");
Mockito.when(myObject.myFunction(myParameter)).thenReturn("otherResult");
Run Code Online (Sandbox Code Playgroud)

因此,而不是仅仅使用参数来确定结果.它使用参数内的属性值来确定结果.

因此,当代码执行时,它的行为就像这样

public void myTestMethod(MyParameter myParameter,MyObject myObject){
    myParameter.setProperty("value");
    System.out.println(myObject.myFunction(myParameter));// outputs myResult

    myParameter.setProperty("otherValue");
    System.out.println(myObject.myFunction(myParameter));// outputs otherResult
}
Run Code Online (Sandbox Code Playgroud)

目前的解决方案,希望能提出更好的建议.

private class MyObjectMatcher extends ArgumentMatcher<MyObject> {

    private final String compareValue;

    public ApplicationContextMatcher(String compareValue) {
        this.compareValue= compareValue;
    }

    @Override
    public boolean matches(Object argument) {
        MyObject item= (MyObject) argument;
        if(compareValue!= null){
            if (item != null) {
                return compareValue.equals(item.getMyParameter());
            }
        }else {
            return item == null || item.getMyParameter() == null;
        }
        return false;
    }
}

public void initMock(MyObject myObject){ …
Run Code Online (Sandbox Code Playgroud)

java mockito

53
推荐指数
4
解决办法
5万
查看次数

Mockito.mock(SomeClass)和@Mock注释有什么区别?

Mockito.mock(Class<T> classToMock)方法和@Mock注释有什么区别?它们是一样的吗?

例如,是这样的:

private TestClass test = Mockito.mock(TestClass.class);
Run Code Online (Sandbox Code Playgroud)

同样如下:

@Mock
private TestClass test;
Run Code Online (Sandbox Code Playgroud)

java junit unit-testing mocking mockito

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

使用Mockito,如何验证方法是否具有某个参数?

我正在使用Mockito 1.9.0.我如何验证一个方法只被调用一次,并且传递给它的一个字段包含一定的值?在我的JUnit测试中,我有

@Before
public void setupMainProg() { 
    // Initialize m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc
    ...
    m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
}   // setupMainProg

@Test
public void testItAll() throws GeneralSecurityException, IOException { 
    m_prog.work();  
}
Run Code Online (Sandbox Code Playgroud)

方法"work"调用"m_orderSvc"方法(传递给对象的参数之一)."m_orderSvc"又包含一个成员字段"m_contractsDao".我想验证"m_contractsDao.save"只被调用一次,并且传递给它的参数包含一个特定值.

这可能有点令人困惑.让我知道如何澄清我的问题,我很高兴这样做.

java mocking mockito

52
推荐指数
3
解决办法
10万
查看次数

我可以延迟使用Mockito的方法响应吗?

我现在正在编写单元测试.我需要用Mockito模拟长期方法来测试我的实现的超时处理.Mockito可以吗?

像这样的东西:

when(mockedService.doSomething(a, b)).thenReturn(c).after(5000L);
Run Code Online (Sandbox Code Playgroud)

java junit mocking mockito

52
推荐指数
3
解决办法
3万
查看次数

PowerMock + Mockito VS Mockito一个人

任何人都可以总结一下,具体功能是什么让你在Mockito上添加PowerMock?

到目前为止,我发现了这些:

  • 模拟静态,最终和私有方法
  • 删除静态初始化程序
  • 允许在没有依赖注入的情况下进行模拟 - 这一点对我来说并不清楚.你能详细说说吗?

它是否添加了其他内容?你能用几行总结一下吗?

使用PowerMock时是否需要牺牲一些东西?

java mocking mockito powermock

51
推荐指数
3
解决办法
3万
查看次数

@Mock注释后,mock实例为null

我尝试运行此测试:

    @Mock IRoutingObjHttpClient routingClientMock;
    @Mock IRoutingResponseRepository routingResponseRepositoryMock;


    @Test
    public void testSendRoutingRequest() throws Exception {
        CompleteRoutingResponse completeRoutingResponse = new CompleteRoutingResponse();
        completeRoutingResponse.regression_latencyMillis = 500L;

        Mockito.when(routingClientMock.sendRoutingRequest(any(RoutingRequest.class))).thenReturn(completeRoutingResponse);

        RoutingObjHttpClientWithReRun routingObjHttpClientWithReRun = new RoutingObjHttpClientWithReRun
                (routingClientMock, routingResponseRepositoryMock);

...
    }
Run Code Online (Sandbox Code Playgroud)

但我得到NullPointerException:

Mockito.when(routingClientMock.

我错过了什么?

java junit unit-testing mocking mockito

50
推荐指数
7
解决办法
4万
查看次数

标签 统计

mockito ×10

java ×9

junit ×6

mocking ×5

unit-testing ×3

powermock ×2

android ×1

slf4j ×1