Tag: mockito

如何validation方法是否通过mockito从具有相同类的其他方法调用

我想测试一些在同一个类中调用其他人的方法。 它基本上是相同的方法,但参数较少,因为数据库中有一些默认值。 我在这上面展示 public class A{ Integer quantity; Integer price; A(Integer q, Integer v){ this quantity = q; this.price = p; } public Float getPriceForOne(){ return price/quantity; } public Float getPrice(int quantity){ return getPriceForOne()*quantity; } } 所以我想测试是否在调用方法getPrice(int)时调用方法getPriceForOne()。 基本上调用普通方法getPrice(int)和mock getPriceForOne。 import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; …. public class MyTests { A mockedA = createMockA(); @Test […]

在Spring 3中创建单一测试

我开始测试应用程序,我想创建几个测试来学习Spring中的Mockito。 我一直在阅读一些信息,但我有一些普遍的疑问,我想问。 我见过Mockito测试,他们用类: @RunWith(MockitoJUnitRunner.class)注释类的测试,而在Spring文档中使用@RunWith(SpringJUnit4ClassRunner.class) 。 我不知道它们之间有什么区别,我应该将哪一个用于测试使用Mockito的Spring应用程序。 由于我还没有看到任何有测试的实际应用程序,我想知道开发人员会做的典型测试。 例如,在用户的典型CRUD应用程序(用户可以创建,更新……)中,任何人都可以进行常规测试。 谢谢。

Mockito:嘲笑一个将在for循环中循环的arraylist

我有一个测试方法,其中包含以下代码段: private void buildChainCode(List lines){ for(TracedPath path : lines){ /…/ } } 我的unit testing代码如下所示: public class ChainCodeUnitTest extends TestCase { private @Mock List listOfPaths; private @Mock TracedPath tracedPath; protected void setUp() throws Exception { super.setUp(); MockitoAnnotations.initMocks(this); } public void testGetCode() { when(listOfPaths.get(anyInt())).thenReturn(tracedPath); ChainCode cc = new ChainCode(); cc.getCode(listOfPaths); /…/ } } 问题是,在运行测试时,测试代码永远不会进入for循环。 什么时候我应该指定条件,以便输入for循环? 目前我已经指定了when(listOfPaths.get(anyInt())).thenReturn(tracedPath) ,但我想它从未使用过。

使用Mockito模拟方法的局部变量

我有一个需要经过测试的A级课程。 以下是A的定义: public class A { public void methodOne(int argument) { //some operations methodTwo(int argument); //some operations } private void methodTwo(int argument) { DateTime dateTime = new DateTime(); //use dateTime to perform some operations } } 并且基于dateTime值,一些数据将被操纵,从数据库中检索。 对于此数据库,值通过JSON文件保留。 这使事情变得复杂。 我需要的是在测试时将dateTime设置为某个特定日期。 有没有办法可以使用mockito模拟局部变量的值?

如何在Junit中使用@InjectMocks和@Autowired注释

我有一个A类,它使用3个不同的类和自动assembly public class A () { @Autowired private B b; @Autowired private C c; @Autowired private D d; } 在测试它们时,我希望只有2个类(B&C)作为模拟,并且将D类自动assembly为正常运行,此代码对我不起作用: @RunWith(MockitoJUnitRunner.class) public class aTest () { @InjectMocks private A a; @Mock private B b; @Mock private C c; @Autowired private D d; } 甚至可以这样做吗?

@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); … } 但我得到NullPointerException: Mockito.when(routingClientMock. 我错过了什么?

将模拟注入Spring MockMvc WebApplicationContext

我正在使用Spring-boot测试(通过JUnit4和Spring MockMvc)一个REST服务适配器。 适配器只是将对其发出的请求传递给另一个REST服务(使用自定义RestTemplate ),并将其他数据附加到响应中。 我想运行MockMvc测试来执行控制器集成测试,但是想要使用模拟覆盖控制器中的RestTemplate ,以允许我预定义第三方REST响应并防止它在每次测试期间被命中。 我已经能够通过实例化MockMvcBuilders.standAloneSetup()并将其传递给要测试的控制器来完成此操作,并按照本文(以及我的设置)中所列的模拟注入,但是我无法使用MockMvcBuilders.webAppContextSetup() 。 我已经阅读了其他几篇文章,其中没有一篇文章回答了如何实现这一目标的问题。 我想使用实际的Spring应用程序上下文进行测试,而不是单独使用,以防止应用程序可能增长时出现任何差距。 编辑:我使用Mockito作为我的模拟框架,并试图将其中一个模拟注入上下文。 如果没有必要,那就更好了。 控制器: @RestController @RequestMapping(Constants.REQUEST_MAPPING_PATH) public class Controller{ @Autowired private DataProvider dp; @Autowired private RestTemplate template; @RequestMapping(value = Constants.REQUEST_MAPPING_RESOURCE, method = RequestMethod.GET) public Response getResponse( @RequestParam(required = true) String data, @RequestParam(required = false, defaultValue = “80”) String minScore ) throws Exception { Response resp = […]

如何使用Mockito测试DAO方法?

我已经开始发现Mockito图书馆了,有一个问题,我找不到合适的答案。 如果我在我的UserDAO类中有这样的方法,可以将用户保存在数据库中: public class UserDAO{ … public void create(User user) { Connection connection = null; PreparedStatement pstmt = null; ResultSet generatedKeys = null; try { connection = getConnection(); pstmt = connection.prepareStatement(INSERT_USER, PreparedStatement.RETURN_GENERATED_KEYS); int counter = 1; pstmt.setString(counter++, user.getFirstName()); pstmt.setString(counter++, user.getLastName()); pstmt.setString(counter++, user.getEmail()); pstmt.setString(counter++, user.getPassword()); pstmt.setString(counter++, user.getRole()); pstmt.setString(counter, user.getLang()); pstmt.execute(); connection.commit(); generatedKeys = pstmt.getGeneratedKeys(); if (generatedKeys.next()) […]

如何用NoSuchAlgorithmException和KeyStoreException覆盖JUnit的块捕获

我想覆盖getKeyStore()方法,但我不知道如何为NoSuchAlgorithmException,KeyStoreException,UnrecoverableKeyException和CertificateException覆盖catch块。 我的方法是: public static KeyManagerFactory getKeyStore(String keyStoreFilePath) throws IOException { KeyManagerFactory keyManagerFactory = null; InputStream kmf= null; try { keyManagerFactory = KeyManagerFactory.getInstance(“SunX509”); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keystoreStream = new FileInputStream(keyStoreFilePath); keyStore.load(keystoreStream, “changeit”.toCharArray()); kmf.init(keyStore, “changeit”.toCharArray()); } catch (NoSuchAlgorithmException e) { LOGGER.error(ERROR_MESSAGE_NO_SUCH_ALGORITHM + e); } catch (KeyStoreException e) { LOGGER.error(ERROR_MESSAGE_KEY_STORE + e); } catch (UnrecoverableKeyException e) { […]

测试powermock模拟http服务器超时以进行客户端调用

我需要为connectTimeout和SocketTimeoutexception编写测试用例。 我使用powerMock来创建模拟对象。 以下是我的代码。 但我的模拟对象得到空指针exception。 任何帮助赞赏 package com.util; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import org.json.JSONObject; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; import org.powermock.modules.testng.PowerMockObjectFactory; import org.powermock.modules.testng.PowerMockTestCase; import org.testng.Assert; import org.testng.IObjectFactory; import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; @PowerMockIgnore(“javax.management.*”) @SuppressStaticInitializationFor(“com.Sender”) @PrepareForTest(Sender.class) public class SenderCatalogTest extends PowerMockTestCase{ @ObjectFactory public IObjectFactory getObjectFactory() { return new PowerMockObjectFactory(); } @Test […]