用参数模拟构造函数

用参数模拟构造函数,第1张

用参数模拟构造函数

您发布的代码适用于最新版本的Mockito和Powermockito。也许您还没有准备A?试试这个:

A.java

public class A {     private final String test;    public A(String test) {        this.test = test;    }    public String check() {        return "checked " + this.test;    }}

MockA.java

import static org.hamcrest.MatcherAssert.assertThat;import static org.hamcrest.Matchers.equalTo;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;import org.junit.Test;import org.junit.runner.RunWith;import org.mockito.Mockito;import org.powermock.api.mockito.PowerMockito;import org.powermock.core.classloader.annotations.PrepareForTest;import org.powermock.modules.junit4.PowerMockRunner;@RunWith(PowerMockRunner.class)@PrepareForTest(A.class)public class MockA {    @Test    public void test_not_mocked() throws Throwable {        assertThat(new A("random string").check(), equalTo("checked random string"));    }    @Test    public void test_mocked() throws Throwable {         A a = mock(A.class);          when(a.check()).thenReturn("test");         PowerMockito.whenNew(A.class).withArguments(Mockito.anyString()).thenReturn(a);         assertThat(new A("random string").check(), equalTo("test"));    }}

两项测试均应通过Mockito 1.9.0,powermockito 1.4.12和junit 4.8.2通过



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5487682.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存