我是Mockito的初学者.
SUT Foo有一个合作者,Bar在一个特定的测试用例中,Foo不应该调用任何方法Bar.
我该怎么做验证呢?
我有一个类似于void方法的模拟类
public class Mock {
public void method(String string) {
// doSomething
}
}
Run Code Online (Sandbox Code Playgroud)
我不关心这个方法做什么,但我想得到String发送.
这个String实际上是一个JSON格式的对象,我正在测试的方法是根据最初发送的字符串修改这个对象(很随意吧).
method(String json) {
Object obj = unparse(json);
obj.setRandomValue(random);
String parsed = parse(obj);
Mock.method(parsed);
}
Run Code Online (Sandbox Code Playgroud)
我想看看之前为null的"randomValue"是否实际上是在方法调用之后随机设置的.
最好的方法是拦截json,解析它并检查对象.
有一种方法有可变参数:
class A {
public void setNames(String... names) {}
}
Run Code Online (Sandbox Code Playgroud)
现在我想用它来模拟它mockito,并捕获传递给它的名字.但我找不到一种方法来捕获任意数量的名字,我只能这样得到它们:
ArgumentCaptor<String> captor1 = ArgumentCaptor.fromClass(String.class);
ArgumentCaptor<String> captor2 = ArgumentCaptor.fromClass(String.class);
A mock = Mockito.mock(A.class);
mock.setNames("Jeff", "Mike");
Mockito.verity(mock).setNames(captor1.capture(), captor2.capture());
String name1 = captor1.getValue(); // Jeff
String name2 = captor2.getValue(); // Mike
Run Code Online (Sandbox Code Playgroud)
如果我传递三个名字,它就无法工作,我必须定义一个captor3来捕获第三个名字.
怎么解决?
我正在使用Context来访问WifiManager和BluetoothManager等系统级服务.如何使用Mockito模拟这个getApplicationContext()?
我有一个Foo方法接口int Foo.bar(int),我想用Mockito模拟.99如果我传入,我希望模拟的方法返回1,但所有其他值将抛出异常.我可以这样做吗?
final Foo foo = mock(Foo.class);
when(foo.bar(1)).thenReturn(99);
when(foo.bar(anyInt())).thenThrow(new IllegalArgumentException());
Run Code Online (Sandbox Code Playgroud)
换句话说,1优先考虑anyInt()?我不希望它抛出异常1.该文档说,对于多个定义,最后的定义是比较重要的,但我不能告诉这是否意味着对于相同的参数或没有.如果它适用于此,我是否需要先定义通配符anyInt()?或者两者甚至有任何关系,因为其中一个是匹配器而另一个只是一个值?
我有一项服务,我需要通过休息询问外部服务器以获取一些信息:
public class SomeService {
public List<ObjectA> getListofObjectsA() {
List<ObjectA> objectAList = new ArrayList<ObjectA>();
ParameterizedTypeReference<List<ObjectA>> typeRef = new ParameterizedTypeReference<List<ObjectA>>() {};
ResponseEntity<List<ObjectA>> responseEntity = restTemplate.exchange("/objects/get-objectA", HttpMethod.POST, new HttpEntity<>(ObjectAList), typeRef);
return responseEntity.getBody();
}
}
Run Code Online (Sandbox Code Playgroud)
我该如何编写JUnit测试getListofObjectsA()?
我试过以下:
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
private MockRestServiceServer mockServer;
@Mock
private RestTemplate restTemplate;
@Inject
private SomeService underTest;
@Before
public void setup() {
mockServer = MockRestServiceServer.createServer(restTemplate);
underTest = new SomeService(restTemplate);
mockServer.expect(requestTo("/objects/get-objectA")).andExpect(method(HttpMethod.POST))
.andRespond(withSuccess("{json list response}", MediaType.APPLICATION_JSON));
}
@Test
public void testGetObjectAList() {
List<ObjectA> res = underTest.getListofObjectsA();
Assert.assertEquals(myobjectA, …Run Code Online (Sandbox Code Playgroud) 我有以下抽象单元测试类,我的所有具体单元测试类都扩展了它:
@ExtendWith(SpringExtension.class)
//@ExtendWith(MockitoExtension.class)
@SpringBootTest(
classes = PokerApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
public abstract class AbstractUnitTests {
@MockBean
public RoundService roundService;
@MockBean
public RoundRepository roundRepository;
}
Run Code Online (Sandbox Code Playgroud)
@ExtendWith(SpringExtension.class)使用or 和有什么不一样@ExtendWith(MockitoExtension.class)?
我问,使用任何一个注释似乎都没有什么区别,并且两者在我的代码中分别工作 - 允许我使用 Junit5。那么为什么两者都有效呢?
具体测试类:
@DisplayName("Test RoundService")
public class RoundsServiceTest extends AbstractUnitTests {
private static String STUB_USER_ID = "user3";
// class under test
@InjectMocks
RoundService roundService;
private Round round;
private ObjectId objectId;
@BeforeEach //note this replaces the junit 4 @Before
public void setUp() {
initMocks(this);
round = Mocks.round(); …Run Code Online (Sandbox Code Playgroud) 我有一个方法我想要存根但它有很多参数.我怎样才能避免模拟所有参数但仍然存根方法.
例如:
//Method to stub
public void myMethod(Bar bar, Foo foo, FooBar fooBar, BarFoo barFoo, .....endless list of parameters..);
Run Code Online (Sandbox Code Playgroud) 需要帮助使用Mockito和JUnit4编写以下代码的单元测试,
public class MyFragmentPresenterImpl {
public Boolean isValid(String value) {
return !(TextUtils.isEmpty(value));
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:MyFragmentPresenter mMyFragmentPresenter
@Before
public void setup(){
mMyFragmentPresenter=new MyFragmentPresenterImpl();
}
@Test
public void testEmptyValue() throws Exception {
String value=null;
assertFalse(mMyFragmentPresenter.isValid(value));
}
Run Code Online (Sandbox Code Playgroud)
但它返回以下异常,
java.lang.RuntimeException:未模拟android.text.TextUtils中的方法isEmpty.有关详细信息,请参阅http://g.co/androidstudio/not-mocked.在android.text.TextUtils.isEmpty(TextUtils.java)....
我正在为一个具有2级依赖注入的类编写测试用例.我使用@Spy注释作为1级依赖注入对象,我想模拟第二级注入.但是,我一直在第二级获得空指针异常.有没有办法将模拟注入@Spy对象?
public class CarTestCase{
@Mock
private Configuration configuration;
@Spy
private Engine engine;
@InjectMocks
private Car car;
@Test
public void test(){
Mockito.when(configuration.getProperties("")).return("Something");
car.drive();
}
}
public class Car{
@Inject
private Engine engine;
public void drive(){
engine.start();
}
}
public class Engine{
@Inject
private Configuration configuration;
public void start(){
configuration.getProperties(); // null pointer exception
}
}
Run Code Online (Sandbox Code Playgroud) mockito ×10
java ×7
mocking ×3
unit-testing ×3
android ×2
android-wifi ×1
bluetooth ×1
junit ×1
junit4 ×1
junit5 ×1
spring ×1
spring-boot ×1
stubbing ×1