使用Mockito示例页面中最基本的示例,我能够在JUnit中成功运行.
但是,当我在Spock中运行相同的测试时,它会失败.
JUnit/Java版本(通过):
import org.junit.Test;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class SimpleJunitTest
{
@Test
public void basicMockTest()
{
List mockedList = mock(List.class);
//using mock object
mockedList.add("one");
mockedList.clear();
//verification
verify(mockedList).add("one");
verify(mockedList).clear();
}
}
Run Code Online (Sandbox Code Playgroud)
Spock/Groovy版本(失败):
import static org.mockito.Mockito.mock
import static org.mockito.Mockito.verify
class SimpleSpockTest extends spock.lang.Specification
{
def "Basic Mock Test"()
{
given:
//mock creation
List mockedList = mock(List.class);
when:
//using mock object
mockedList.add("one");
mockedList.clear();
then:
//verification
verify(mockedList).add("one");
verify(mockedList).clear();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我在Spock测试失败时得到的错误:
Condition not satisfied:
verify(mockedList).add("one")
| …Run Code Online (Sandbox Code Playgroud) when(candidateService.findById(1)).thenReturn(new Candidate());
Run Code Online (Sandbox Code Playgroud)
我想为任何整数扩展此行为(不一定是1)
如果我啰嗦
when(candidateService.findById( any(Integer.class) )).thenReturn(new Candidate());
Run Code Online (Sandbox Code Playgroud)
我有编译错误
CandidateService类型中的方法findById(Integer)不适用于参数(Matcher)
UPDATE
进口:
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.HashSet;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
Run Code Online (Sandbox Code Playgroud) 我正在试图窥探一个Object,我想在构造函数调用之前存根一个由构造函数调用的方法.
我的班级看起来像这样:
public class MyClass {
public MyClass() {
setup();
}
public void setup() {
}
}
Run Code Online (Sandbox Code Playgroud)
不得调用安装方法.那么,我如何监视这个方法(和存根设置,以便它什么都不做)?
它可以很好地模拟方法,但我想进行单元测试MyClass,所以我需要其他方法.
之所以需要存根设置方法以便它什么都不做:
我正在编写一个乐高机器人(lejos)并且我在设置中放置了一些机器人需要工作的代码.但是,当我在TinyVM(安装在机器人上的VM)之外调用它时,java崩溃,因为VM尚未正确初始化(因为测试在我的PC上运行).对于单元测试,设置并不重要.
我不能存根类/方法设置调用,因为它们中的一些是公共静态最终变量.
以下方法的等效方法是什么:
@Mock
MyType1 myType1;
@Autowired
@InjectMocks
MyType2 myType2;
Run Code Online (Sandbox Code Playgroud)
我可以代替@Mock使用mock(MyType1.class).
但是如何@InjectMocks用方法调用替换?像这样的东西:
injectMocks(MyType2.class)
Run Code Online (Sandbox Code Playgroud) 我正在尝试构建一个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) 看看下面的代码,我只希望调用getSand()发生一次,但是测试失败,只有四次调用.这些电话在哪里发生?我想写一个测试来确保只进行一次调用getSand().
资源
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DeepSandTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
SandBox mockSandBox;
@Test
public void should(){
when(mockSandBox.getSand().doA()).thenReturn(1);
when(mockSandBox.getSand().doB()).thenReturn(1);
when(mockSandBox.getSand().doC()).thenReturn(1);
DeepSand deepSand = new DeepSand(mockSandBox);
deepSand.getTipple();
verify(mockSandBox, times(1)).getSand();
}
public class DeepSand{
private SandBox sandBox;
public DeepSand(SandBox sandBox) {
this.sandBox = sandBox;
}
public void getTipple(){
Sand sand = sandBox.getSand();
sand.doA();
sand.doB();
sand.doC();
}
}
public interface SandBox{ …Run Code Online (Sandbox Code Playgroud) 我在我的JUnit中测试Restful端点并在列表中获得如下所示的异常,该异常作为save方法中的参数出现,
**"Argument(s) are different! Wanted:"**
save(
"121",
[com.domain.PP@6809cf9d,
com.domain.PP@5925d603]
);
Actual invocation has different arguments:
save(
"121",
[com.domain.PP@5b6e23fd,
com.domain.PP@1791fe40]
);
Run Code Online (Sandbox Code Playgroud)
当我调试代码时,代码在下面的验证行中断开并引发了上述异常.看起来save方法中"testpPList"内的参数是不同的.我不知道它是如何变得不同,因为我正确地在我的JUNit中构造它们然后调用RestFul URL.
请求您的宝贵意见.谢谢.
码:
@Test
public void testSelected() throws Exception {
mockMvc.perform(put("/endpointURL")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(testObject)))
.andExpect(status().isOk());
verify(programServiceMock, times(1)).save(id, testpPList);
verifyNoMoreInteractions(programServiceMock);
}
Run Code Online (Sandbox Code Playgroud)
控制器方法:
@RequestMapping(value = "/endpointURL", method = RequestMethod.PUT)
public @ResponseBody void uPP(@PathVariable String id, @RequestBody List<PPView> pPViews) {
// Code to construct the list which is passed into the save method below
save(id, pPList);
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试模拟私有静态方法anotherMethod().见下面的代码
public class Util {
public static String method(){
return anotherMethod();
}
private static String anotherMethod() {
throw new RuntimeException(); // logic was replaced with exception.
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试代码
@PrepareForTest(Util.class)
public class UtilTest extends PowerMockTestCase {
@Test
public void should_prevent_invoking_of_private_method_but_return_result_of_it() throws Exception {
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.class, "anotherMethod").thenReturn("abc");
String retrieved = Util.method();
assertNotNull(retrieved);
assertEquals(retrieved, "abc");
}
}
Run Code Online (Sandbox Code Playgroud)
但是我运行它的每个瓷砖都得到了这个例外
java.lang.AssertionError: expected object to not be null
Run Code Online (Sandbox Code Playgroud)
我想我在做嘲弄事情时做错了.任何想法我该如何解决?
如何@Scheduled在spring-boot应用程序中测试作业任务?
package com.myco.tasks;
public class MyTask {
@Scheduled(fixedRate=1000)
public void work() {
// task execution logic
}
}
Run Code Online (Sandbox Code Playgroud) 我已经开发了一个使用rxJava改造的Android应用程序,现在我正在尝试使用Mockito设置单元测试,但我不知道如何模拟api响应以创建不做真正的测试电话但有假响应.
例如,我想测试方法syncGenres对我的SplashPresenter工作正常.我的课程如下:
public class SplashPresenterImpl implements SplashPresenter {
private SplashView splashView;
public SplashPresenterImpl(SplashView splashView) {
this.splashView = splashView;
}
@Override
public void syncGenres() {
Api.syncGenres(new Subscriber<List<Genre>>() {
@Override
public void onError(Throwable e) {
if(splashView != null) {
splashView.onError();
}
}
@Override
public void onNext(List<Genre> genres) {
SharedPreferencesUtils.setGenres(genres);
if(splashView != null) {
splashView.navigateToHome();
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
Api类就像:
public class Api {
...
public static Subscription syncGenres(Subscriber<List<Genre>> apiSubscriber) {
final Observable<List<Genre>> call = ApiClient.getService().syncGenres();
return call
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(apiSubscriber);
} …Run Code Online (Sandbox Code Playgroud)