Best Mockito code snippet using org.mockito.android.internal.creation.AndroidTempFileLocator.getCacheDirFromInstrumentationRegistry
Source: AndroidTempFileLocator.java
...18 }19 } catch (Throwable ignored) {20 }21 if (t == null) {22 t = getCacheDirFromInstrumentationRegistry("android.support.test.InstrumentationRegistry");23 }24 if (t == null) {25 t = getCacheDirFromInstrumentationRegistry("androidx.test.InstrumentationRegistry");26 }27 if (t == null) {28 try {29 Class<?> clazz = Class.forName("dalvik.system.PathClassLoader");30 Field pathField = clazz.getDeclaredField("path");31 pathField.setAccessible(true);32 String pathFromThisClassLoader = (String) pathField.get(AndroidTempFileLocator.class.getClassLoader());33 File[] results = guessPath(pathFromThisClassLoader);34 if (results.length > 0) {35 t = results[0];36 }37 } catch (Throwable ignored) {38 }39 }40 target = t;41 }42 private static File getCacheDirFromInstrumentationRegistry(String className) {43 try {44 Class<?> clazz = Class.forName(className);45 Object context = clazz.getDeclaredMethod("getTargetContext").invoke(clazz);46 return (File) context.getClass().getMethod("getCacheDir").invoke(context);47 } catch (Throwable ignored) {48 }49 return null;50 }51 private static File[] guessPath(String input) {52 List<File> results = new ArrayList<File>();53 for (String potential : splitPathList(input)) {54 if (!potential.startsWith("/data/app/")) {55 continue;56 }...
getCacheDirFromInstrumentationRegistry
Using AI Code Generation
1val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()2val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()3val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()4val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()5val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()6val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()7val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()8val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()9val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()10val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()11val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()12val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()13val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()14val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()15val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()16val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()17val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()18val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()19val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()20val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()21val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()22val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()23val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()24val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()25val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()26val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()27val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()28val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()29val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()30val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()31val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()32val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()33val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()34val mockitoCacheDir = getCacheDirFromInstrumentationRegistry()
getCacheDirFromInstrumentationRegistry
Using AI Code Generation
1File cacheDir = AndroidTempFileLocator.getCacheDirFromInstrumentationRegistry();2File file = File.createTempFile("test", "txt", cacheDir);3List<String> list = mock(List.class);4list.add(file.getAbsolutePath());5file.delete();6cacheDir.delete();7File cacheDir = AndroidTempFileLocator.getCacheDirFromInstrumentationRegistry();8File file = File.createTempFile("test", "txt", cacheDir);9List<String> list = mock(List.class);10list.add(file.getAbsolutePath());11file.delete();12cacheDir.delete();13File cacheDir = AndroidTempFileLocator.getCacheDirFromInstrumentationRegistry();14File file = File.createTempFile("test", "txt", cacheDir);15List<String> list = mock(List.class);16list.add(file.getAbsolutePath());17file.delete();18cacheDir.delete();19File cacheDir = AndroidTempFileLocator.getCacheDirFromInstrumentationRegistry();20File file = File.createTempFile("test
getCacheDirFromInstrumentationRegistry
Using AI Code Generation
1testOptions {2}3@RunWith(RobolectricTestRunner::class)4class TestClass {5 fun test() {6 val cacheDir = getCacheDirFromInstrumentationRegistry()7 }8}
Unable to mock Service class in Spring MVC Controller tests
Stubbing a method that takes Class<T> as parameter with Mockito
How to android unit test and mock a static method
How to test anonymous methods with JUnit or Mockito?
IntelliJ Idea not resolving Mockito and JUnit dependencies with Maven
Mockito - mocking classes with native methods
TestNG unit test not working after annotating service to test with @Retention, @Transactional, @Inherited
Using Mockito to mock classes with generic parameters
Mockito How to mock only the call of a method of the superclass
Create a JsonProcessingException
Thanks to @J Andy's line of thought, I realised that I had been heading down the wrong path on this. In Update 1 I was trying to inject the mock service into the MockMvc
but after taking a step back I realised that it's not the MockMvc
that was under test, it was the PolicyController
I wanted to test.
To give a bit of background, I wanted to avoid a traditional unit test of the @Controllers in my Spring MVC application because I wanted to test things that are only provided by running the controllers within Spring itself (e.g. RESTful calls to controller actions). This can be achieved by using the Spring MVC Test framework which allows you to run your tests within Spring.
You'll see from the code in my initial question that I was running the Spring MVC tests in a WebApplicationContext
(i.e. this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
) whereas what I should have been doing was running standalone. Running standalone allows me to directly inject the controller I want to test and, therefore, have control over how the service is injected into the controller (i.e. force a mock service to be used).
This is easier explained in code. So for the following controller:
import javax.validation.Valid;
import name.hines.steven.medical_claims_tracker.domain.Benefit;
import name.hines.steven.medical_claims_tracker.domain.Policy;
import name.hines.steven.medical_claims_tracker.services.DomainEntityService;
import name.hines.steven.medical_claims_tracker.services.PolicyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/policies")
public class PolicyController extends DomainEntityController<Policy> {
@Autowired
private PolicyService service;
@RequestMapping(value = "persist", method = RequestMethod.POST)
public String createOrUpdate(@Valid @ModelAttribute("policy") Policy policy, BindingResult result) {
if (result.hasErrors()) {
return "createOrUpdatePolicyForm";
}
service.save(policy);
return "redirect:list";
}
}
I now have the following test class in which the service is successfully mocked out and my test database is no longer hit:
package name.hines.steven.medical_claims_tracker.controllers;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import name.hines.steven.medical_claims_tracker.domain.Policy;
import name.hines.steven.medical_claims_tracker.services.PolicyService;
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;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:/applicationContext.xml" })
public class PolicyControllerTest {
@Mock
PolicyService policyService;
@InjectMocks
PolicyController controllerUnderTest;
private MockMvc mockMvc;
@Before
public void setup() {
// this must be called for the @Mock annotations above to be processed
// and for the mock service to be injected into the controller under
// test.
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(controllerUnderTest).build();
}
@Test
public void createOrUpdateFailsWhenInvalidDataPostedAndSendsUserBackToForm() throws Exception {
// POST no data to the form (i.e. an invalid POST)
mockMvc.perform(post("/policies/persist")).andExpect(status().isOk())
.andExpect(model().attributeHasErrors("policy"))
.andExpect(view().name("createOrUpdatePolicy"));
}
@Test
public void createOrUpdateSuccessful() throws Exception {
when(policyService.save(isA(Policy.class))).thenReturn(new Policy());
mockMvc.perform(
post("/policies/persist").param("companyName", "Company Name")
.param("name", "Name").param("effectiveDate", "2001-01-01"))
.andExpect(status().isMovedTemporarily()).andExpect(model().hasNoErrors())
.andExpect(redirectedUrl("list"));
}
}
I'm still very much learning when it comes to Spring so any comments that will improve my explanation would be welcomed. This blog post was helpful to me in coming up with this solution.
Check out the latest blogs from LambdaTest on this topic:
With the rise of Agile, teams have been trying to minimize the gap between the stakeholders and the development team.
Technical debt was originally defined as code restructuring, but in today’s fast-paced software delivery environment, it has evolved. Technical debt may be anything that the software development team puts off for later, such as ineffective code, unfixed defects, lacking unit tests, excessive manual tests, or missing automated tests. And, like financial debt, it is challenging to pay back.
Agile has unquestionable benefits. The mainstream method has assisted numerous businesses in increasing organizational flexibility as a result, developing better, more intuitive software. Distributed development is also an important strategy for software companies. It gives access to global talent, the use of offshore outsourcing to reduce operating costs, and round-the-clock development.
Desired Capabilities is a class used to declare a set of basic requirements such as combinations of browsers, operating systems, browser versions, etc. to perform automated cross browser testing of a web application.
Lack of training is something that creates a major roadblock for a tester. Often, testers working in an organization are all of a sudden forced to learn a new framework or an automation tool whenever a new project demands it. You may be overwhelmed on how to learn test automation, where to start from and how to master test automation for web applications, and mobile applications on a new technology so soon.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!