mockito | popular Mocking framework for unit tests | Unit Testing library
kandi X-RAY | mockito Summary
Support
Quality
Security
License
Reuse
- Matches a method invocation .
- Returns the return value for the given type .
- Trigger retransformation .
- Prints a value as a string .
- make sure arguments are valid
- Filter the stack trace .
- Registers type variables on the given class .
- Creates the mock object .
- Proxies a new instance of a given field .
- Process annotation .
mockito Key Features
mockito Examples and Code Snippets
Trending Discussions on mockito
Trending Discussions on mockito
QUESTION
I’m using Mockito for unit testing and I want to skip the execution of a method.
I referred to this ticket Skip execution of a line using Mockito. Here, I assume doSomeTask() and createLink() methods are in different classes. But in my case, both the methods are in the same class (ActualClass.java).
//Actual Class
public class ActualClass{
//The method being tested
public void method(){
//some business logic
validate(param1, param2);
//some business logic
}
public void validate(arg1, arg2){
//do something
}
}
//Test class
public class ActualClassTest{
@InjectMocks
private ActualClass actualClassMock;
@Test
public void test_method(){
ActualClass actualClass = new ActualClass();
ActualClass spyActualClass = Mockito.spy(actualClass);
// validate method creates a null pointer exception, due to some real time data fetch from elastic
doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
actualClassMock.method();
}
}
Since there arises a null pointer exception when the validate method is executed, I’m trying to skip the method call by spying the ActualClass object as stated in the ticket I mentioned above. Still, the issue is not resolve. The validate method gets executed and creates a null pointer exception due to which the actual test method cannot be covered.
So, how do I skip the execution of the validate() method that is within the same class.
ANSWER
Answered 2022-Mar-04 at 09:36You must always use your spy class when calling method()
.
@Test
public void test_method(){
ActualClass spyActualClass = Mockito.spy(actualClassMock);
doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
spyActualClass.method();
}
In practice, instead of
actualClassMock.method();
you must use
spyActualClass.method();
QUESTION
Trying to update my project from Java 11 to Java 17 and got an unexpected error from Mockito in a specific test.
mock(java.util.Random.class);
Throws
Feb 04, 2022 3:07:01 PM com.google.inject.internal.MessageProcessor visit
INFO: An exception was caught and reported. Message: java.lang.IllegalAccessException: class
net.bytebuddy.description.annotation.AnnotationDescription$ForLoadedAnnotation cannot access interface
jdk.internal.util.random.RandomSupport$RandomGeneratorProperties (in module java.base)
because module java.base does not export jdk.internal.util.random to unnamed module @2f54a33d
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class java.util.Random.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 17
JVM vendor name : Oracle Corporation
JVM vendor version : 17.0.2+8-86
JVM name : OpenJDK 64-Bit Server VM
JVM version : 17.0.2+8-86
JVM info : mixed mode, sharing
OS name : Mac OS X
OS version : 12.1
Not sure why Mockito is failing on this test.
ANSWER
Answered 2022-Feb-08 at 16:20The issue here is mockito (via ByteBuddy) is trying to use an inaccessible type at runtime (via reflection). From Java 9 onwards, not all modules are accessible unless you explicitly export/open them.
As this is a runtime issue, you can add --add-opens
as a JVM arg/CLI option to make this type accessible.
As per the Oracle guide here, --add-opens
does the following.
If you have to allow code on the classpath to do deep reflection to access nonpublic members, then use the --add-opens runtime option.
If you want to export internal types available in compile time as well, you can use --add-exports
.
To solve your specific issue; use the following.
--add-opens java.base/jdk.internal.util.random=ALL-UNNAMED
.
ALL-UNNAMED
means, a specified package is available in the entire codebase.
However, mocking types that don't belong to you is not a good practice. Maybe, you can simplify this if there's an alternative.
QUESTION
I'm using Kotlin 1.6.10, Mockito 4.0.0 and Java 8 and I have a Java interface defined like this:
public interface MyInterface {
> T doThings(T myObject);
}
An implementation of this interface is used in a Kotlin application and we have a unit test in which we want to make sure that the doThings
method is never called using Mockito. In Java I would just do like this:
verify(myInterfaceInstance, never()).doThings(any());
But if I do this in Kotlin I get a compile-time error:
verify(myInterfaceInstance, never()).doThings(any())
Not enough information to infer type variable D
I understand why this is the case, but I cannot get it to work. In this particular case I really don't care about the generic types, I just want to make sure the doThings
is never called. I've tried a lot of different things, for example:
verify(myInterfaceInstance, never()).doThings>(any())
which fails with:
Type argument is not within its bounds.
Expected:
MyObject<*, Any>!, TypeVariable(D)!>!
Found:
MyObject<*, Any!>!
and I've also tried:
verify(myInterfaceInstance, never()).doThings>(any())
and several other permutations which all seem to fail with roughly the same error message.
So my question is, how can I do the equivalent of Java's verify(myInterfaceInstance, never()).doThings(any());
in Kotlin?
ANSWER
Answered 2022-Jan-26 at 08:45This is not a Mockito answer, but would the Library Mockk help you? MockK is built specifically for Kotlin so it might have better supports for Generics handling.
The verification would look like:
verify(exactly = 0) { yourClass.doThings(any()) };
QUESTION
I am new on Flutter. I have started to writing tests. I saw mockito
and mocktail
as the most used testing libraries. I couldn't find any question/articles that explains differences between them. If there is a experienced developers -who used both of them- can you explain differences/advantages/disadvantages of them? Which one should I prefer?
Thanks in advance!
ANSWER
Answered 2022-Jan-19 at 16:491. Assuming that you are new with Flutter, it would be probably easier for you to utilize the mocktail package.
The main "inconvenience" with the mockito package is that you need to generate the mocks running flutter pub run build_runner build, define meta-annotations like @GenerateMocks, and imports like xxx.mocks.dart, and an extra build_runner dev dependency at your pubspec.yaml.
The mocktail package simplifies mocking: you just need to extend the Mock class. That's it. Without code-generating, annotations, "magic" xxx.mocks.dart imports.
2. Also, you have to keep in mind that the mocktail package is very new and has a stable history of just 10 months. The mockito package is a proven by time and developers library that has almost 8 years of history of stable releases: the library is well-known and is widespread among the Flutter and Dart community.
With the experience, you will better understand which library better fits your projects' needs.
PS: you can take a look at the code snippets of both packages.
The mocktail snippet screenshot:
The mockito snippet screenshot
QUESTION
During unit testing retry the response of the mock seems cached, or most probably I am doing something wrong.
I am trying to request something, if error happened then retry twice with delay of 1 second.
public Mono someMethod(String someParam) {
return someInjectedService.doSomething(someParam)
.doOnError(ex -> System.out.println(ex + ": " + System.currentTimeMillis()))
.retryWhen(Retry.fixedDelay(2, Duration.ofSeconds(1)).filter(ex -> ex instanceof SomeCustomException))
.doOnSuccess(result -> doSomethingOnSuccess(result));
}
My test:
@Test
void testshouldRequestThrice_whenErrorOccurs() {
// Given
String someParam = "testParam";
when(someInjectedService.doSomething(someParam))
.thenReturn(Mono.error(new SomeCustomException("SomeCustomException"))) // 1st response
.thenReturn(Mono.error(new SomeCustomException("SomeCustomException"))) // 2nd response
.thenReturn(Mono.just("SomeValidResponse")); // 3rd valid response
// When
var result = testService.someMethod(someParam).block();
// Then
// Initial request, followed by two retries
verify(someInjectedService, times(3)).doSomething(someParam);
}
here someInjectedService
is a mock.
My plan was to return an exception twice, and on third request return valid response. But what I get is:
org.mockito.exceptions.verification.TooFewActualInvocations: someInjectedService.doSomething("testParam");
Wanted 3 times: -> at shouldRequestThrice_whenErrorOccurs(test.java:138)
But was 1 time:
While I do see 3 prints from .doOnError(ex -> System.out.println(ex + ": " + System.currentTimeMillis()))
block, I feel like the actual request is sent only once.
Thank you in advance,
ANSWER
Answered 2022-Jan-19 at 15:18someInjectedService.doSomething(...)
will indeed technically be called only once.
You could use Mono.defer(() -> someInjectedService.doSomething(someParam))
instead, to ensure the method is effectively called again, which should make your test pass.
QUESTION
I have written a method which asks user to press enter to continue and timeouts after some time. I am facing difficulty in writing Junit tests for this method use Mockito. Below is the method.
private static final ExecutorService l = Executors.newFixedThreadPool(1);
private static String getUserInputWithTimeout(int timeout) {
Callable k = () -> new Scanner(System.in).nextLine();
LocalDateTime start = LocalDateTime.now();
Future g = l.submit(k);
while (ChronoUnit.SECONDS.between(start, LocalDateTime.now()) < timeout) {
if (g.isDone()) {
try {
String choice = g.get();
return choice;
} catch (InterruptedException | ExecutionException | IllegalArgumentException e) {
logger.error("ERROR", e);
g = l.submit(k);
}
}
}
logger.info("Timeout...");
g.cancel(true);
return null;
}
I tried mocking Callable and Future but as this method is creating them locally creating them in Test has no impact.
I tried few things but didnt work as expected I might be doing it wrong.
@Test
public void testgetUserInputWithUserInput() throws Exception {
Scanner scanner = new Scanner(System.in);
Callable callable = PowerMockito.mock(Callable.class);
ExecutorService executorServiceMock = PowerMockito.mock(ExecutorService.class);
Future futureMock = PowerMockito.mock(Future.class);
when(executorServiceMock.submit(any(Callable.class))).thenReturn(futureMock);
assertEquals("", getUserInputWithTimeout(3));
}
ANSWER
Answered 2022-Jan-14 at 11:58I would say you need to slightly change your method, take the callable object out of method and pass it as a parameter, this should solve your problem with mocking.
private static final ExecutorService l = Executors.newFixedThreadPool(1);
private static String getUserInputWithTimeout(int timeout, Callable k) {
LocalDateTime start = LocalDateTime.now();
Future g = l.submit(k);
while (ChronoUnit.SECONDS.between(start, LocalDateTime.now()) < timeout) {
if (g.isDone()) {
try {
String choice = g.get();
return choice;
} catch (InterruptedException | ExecutionException | IllegalArgumentException e) {
logger.error("ERROR", e);
g = l.submit(k);
}
}
}
logger.info("Timeout...");
g.cancel(true);
return null;
}
Your tests should look like below :
@Test
public void testgetUserInputWithUserInput() throws Exception {
String ENTER = " ";
System.setIn(new ByteArrayInputStream(ENTER.getBytes()));
Callable callable = () -> new Scanner(System.in).nextLine();
assertEquals(ENTER, getUserInputWithTimeout(5, callable));
}
QUESTION
I have a controller which gives the user a 403 response unless they are authenticated with a JWT token which is passed as a Bearer token via the authorization header. I'm looking for resources on how to test this with Mockito but I'm not very successful so far as most of them tell me to use the @WithMockUser annotation, which I understand is for Spring security yes, but does not include the mocking for a JWT token. I've tried to mock a few objects such as the UserDetailsClass and the JwtFilter and even hardcoding the bearer token but I think there should be more to it.
@MockBean
private CategoryCommandService categoryCommandService;
@Autowired
private MockMvc mockMvc;
@MockBean
private MyUserDetailsService myUserDetailsService;
@MockBean
private CategoryRepository categoryRepository;
@MockBean
private JwtUtil jwtUtil;
@Autowired
private JwtRequestFilter filter;
@Test
void testCreateCategory() throws Exception {
CategoryCreateDto categoryCreateDto = new CategoryCreateDto("category");
CategoryCreateDto categoryCreateResponseDto = new CategoryCreateDto(UUID.fromString("2da4002a-31c5-4cc7-9b92-cbf0db998c41"), "category");
String jsonCreate = asJsonString(categoryCreateDto);
String jsonResponse = asJsonString(categoryCreateResponseDto);
RequestBuilder request = MockMvcRequestBuilders
.post("/api/adverts/category")
.content(jsonCreate)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb29AZW1haWwuY29tIiwiZXhwIjoxNjM4ODU1MzA1LCJpYXQiOjE2Mzg4MTkzMDV9.q4FWV7yVDAs_DREiF524VZ-udnqwV81GEOgdCj6QQAs")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_JSON);
mockMvc.perform(request).andReturn();
when(categoryCommandService.createCategory(categoryCreateDto)).thenReturn(
categoryCreateResponseDto);
MvcResult mvcResult = mockMvc.perform(request)
.andExpect(status().is2xxSuccessful())
.andExpect(content().json(jsonResponse, true))
.andExpect(jsonPath("$.id").value("2da4002a-31c5-4cc7-9b92-cbf0db998c41"))
.andExpect(jsonPath("$.title").value("category"))
.andReturn();
logger.info(mvcResult.getResponse().getContentAsString());
}
Here my controller:
@CrossOrigin
@RequestMapping("/api/adverts/category")
@RestController
public class CategoryCommandController {
@Autowired
private CategoryCommandService categoryCommandService;
@Autowired
private CategoryRepository categoryRepository;
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity createCategory(@RequestBody CategoryCreateDto categoryCreateDto) {
if (categoryCreateDto.getTitle() != null) {
return new ResponseEntity<>(categoryCommandService.createCategory(categoryCreateDto), HttpStatus.CREATED);
}
else {
return new ResponseEntity<>(new FeedbackMessage("Missing title"), HttpStatus.BAD_REQUEST);
}
}
}
And here my filter:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.example.adverts.SecurityConstants.SIGN_UP_URL;
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
@Autowired
private MyUserDetailsService userDetailsService;
@Autowired
private JwtUtil jwtUtil;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String path = request.getRequestURI();
if (path.equals(SIGN_UP_URL)) {
chain.doFilter(request, response);
return;
}
final String authorizationHeader = request.getHeader("Authorization");
String username = null;
String jwt = null;
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
} else {
response.setStatus(HttpStatus.FORBIDDEN.value());
}
if (username != null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
chain.doFilter(request, response);
}
}
}
And JwtUtil class:
@Service
public class JwtUtil {
private String SECRET_KEY = "secret";
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
public T extractClaim(String token, Function claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
public String generateToken(UserDetails userDetails) {
Map claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
private String createToken(Map claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
.signWith(SignatureAlgorithm.HS256, SECRET_KEY).compact();
}
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
Here is the whole Github branch.
https://github.com/francislainy/adverts-backend/tree/dev_jwt
Thank you.
UPDATE
For clarity if I hardcode a valid token I get a 200 status code but my tests will still fail with nothing returned for content whereas before JWT and Spring security they were passing.
ANSWER
Answered 2021-Dec-26 at 05:59We just fixed the issue (accepting the other answer for being a more elegant solution).
1st and easier option:
Disable filter authentication for controller test classes:
@AutoConfigureMockMvc(addFilters = false)
class CategoryCommandControllerTest {
You can then perhaps test jwt authorization separately.
2nd and perhaps better option:
Remove the extra pieces from the configure method within the WebSecurity class to end up with only this.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
Then under the JwtRequestFilter class add a return when a 403 is caught on the else part of this if block.
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
jwt = authorizationHeader.substring(7);
username = jwtUtil.extractUsername(jwt);
} else {
response.setStatus(HttpStatus.FORBIDDEN.value());
return;
}
And move the doChain.filter piece outside of the other if block.
if (username != null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (jwtUtil.validateToken(jwt, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
// chain.doFilter(request, response);
}
chain.doFilter(request, response);
}
QUESTION
Is it possible in Mockito to return the object that mocked method was called with? Without prior knowing what object it will be.
@Mock
MyObjectRepository myObjectRepository;
...
when(myObjectRepository.save(any(MyObject.class))) //save method returns normally MyObject.class object
.thenReturn(\\the object that method was called with);
I want to return the object that is passed to save method.
ANSWER
Answered 2021-Dec-16 at 12:39The following should work:
when(myObjectRepository.save(any(MyObject.class)))
.then(AdditionalAnswers.returnsFirstArg());
QUESTION
I'm trying to mock sharedPreferences using Mockito in my flutter project. Here is the error log.
package:mockito/src/mock.dart 190:7 Mock._noSuchMethod
package:mockito/src/mock.dart 184:45 Mock.noSuchMethod
test\feature\number_trivia\data\datasource\number_trivia_local_datasource_test.mocks.dart 67:14 MockSharedPreferences.setString
package:clean_arch_tdd/features/number_trivia/data/datasources/number_trivia_local_datasource.dart 31:30 NumberTriviaLocalDataSourceImpl.cacheLastNumberTrivia
test\feature\number_trivia\data\datasource\number_trivia_local_datasource_test.dart 51:18 main..
MissingStubError: 'setString'
No stub was found which matches the arguments of this method call:
setString('CACHED_NUMBER_TRIVIA', '{"text":"Test trivia","number":1}')
Add a stub for this method using Mockito's 'when' API, or generate the mock for MockSharedPreferences with 'returnNullOnMissingStub: true'.
The error refer to this line of code.
local_data_source_test.dart
test('should call sharedPreferences to cache the data', () {
dataSource.cacheLastNumberTrivia(tNumberTriviaModel);
final expectedJsonString = jsonEncode(tNumberTriviaModel.toJson());
verify(mockSharedPreferences.setString(
cachedNumberTrivia, expectedJsonString));
});
local_data_source.dart
@override
Future cacheLastNumberTrivia(NumberTriviaModel triviaToCache) {
return sharedPreferences.setString(
cachedNumberTrivia, jsonEncode(triviaToCache.toJson()));
}
It show that method setString from the mocked sharedPreferences is missing. I already run the pub command to generate the mocks. I also have some test case in the file that use the getString method. And it works fine.
Is there something I'm missing so I can't use the setString method? Or are there any solution to this problem?
Thx in advance.
ANSWER
Answered 2021-Dec-07 at 13:00I actually figured it out, sorry for not posting the answer immediately.
I found myself forgot to call the stub for the setString method. Here is the code.
group('cacheNumberTrivia', () {
const tNumberTriviaModel =
NumberTriviaModel(number: 1, text: 'Test trivia');
test('should call sharedPreferences to cache the data', () async {
when(mockSharedPreferences.setString(any, any))
.thenAnswer((_) async => true);
dataSource.cacheLastNumberTrivia(tNumberTriviaModel);
final expectedJsonString = jsonEncode(tNumberTriviaModel.toJson());
verify(mockSharedPreferences.setString(
cachedNumberTrivia, expectedJsonString));
});
});
The stub was actually this line:
when(mockSharedPreferences.setString(any, any))
.thenAnswer((_) async => true);
I forgot to call the when
method before verifying the result with verify
, hence it throws an error.
QUESTION
Recently updated from Kotlin 1.4.20
to 1.5.30
.
I have this class which used to compile no problem
data class Optional(val value: M?)
However, after upgrading, I get the following exception
org.jetbrains.kotlin.backend.common.BackendException: Backend Internal error: Exception during IR lowering
File being compiled: .../Optional.kt
The root cause java.lang.RuntimeException was thrown at: org.jetbrains.kotlin.backend.jvm.codegen.FunctionCodegen.generate(FunctionCodegen.kt:50)
at org.jetbrains.kotlin.backend.common.CodegenUtil.reportBackendException(CodegenUtil.kt:239)
at org.jetbrains.kotlin.backend.common.CodegenUtil.reportBackendException$default(CodegenUtil.kt:235)
at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invokeSequential(performByIrFile.kt:68)
at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invoke(performByIrFile.kt:55)
at org.jetbrains.kotlin.backend.common.phaser.PerformByIrFilePhase.invoke(performByIrFile.kt:41)
at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:29)
at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
at org.jetbrains.kotlin.backend.common.phaser.CompositePhase.invoke(PhaseBuilders.kt:29)
at org.jetbrains.kotlin.backend.common.phaser.NamedCompilerPhase.invoke(CompilerPhase.kt:96)
at org.jetbrains.kotlin.backend.common.phaser.CompilerPhaseKt.invokeToplevel(CompilerPhase.kt:43)
at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.doGenerateFilesInternal(JvmIrCodegenFactory.kt:191)
at org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory.generateModule(JvmIrCodegenFactory.kt:60)
at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:35)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:321)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:113)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:56)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:169)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:52)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:92)
at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:412)
at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:112)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:358)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally$default(IncrementalCompilerRunner.kt:300)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileImpl$rebuild(IncrementalCompilerRunner.kt:119)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileImpl(IncrementalCompilerRunner.kt:170)
at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:81)
at org.jetbrains.kotlin.daemon.CompileServiceImplBase.execIncrementalCompiler(CompileServiceImpl.kt:607)
at org.jetbrains.kotlin.daemon.CompileServiceImplBase.access$execIncrementalCompiler(CompileServiceImpl.kt:96)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1658)
I get that it's telling me that Any
's toString()
method doesn't have a body as I can see that from looking at the source code.
What I don't understand is how to rectify it.
EDIT
Can confirm this still happens when upgrading to kotlin version 1.6.0
.
It also happens in this data class:
data class Advertisement(
var id: String,
var image: String,
var navUrl: String?
)
My build.gradle
file for this module looks like so:
apply plugin: 'kotlin'
apply plugin: 'kotlin-kapt'
apply plugin: 'com.stustirling.redacted-gradle-plugin'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
implementation "io.reactivex.rxjava2:rxkotlin:$rxKotlinVersion"
implementation "io.reactivex.rxjava2:rxjava:$rxJavaVersion"
implementation "com.jakewharton.timber:timber:$timberVersion"
implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
implementation "com.google.dagger:dagger:$daggerVersion"
kapt "com.google.dagger:dagger-compiler:$daggerVersion"
implementation "org.json:json:$testOrgJsonVersion"
implementation "net.sf.biweekly:biweekly:$biweeklyVersion"
testImplementation "junit:junit:$junitVersion"
testImplementation "org.mockito.kotlin:mockito-kotlin:$mockitoKotlinVersion"
testImplementation "org.mockito:mockito-inline:$mockitoInlineVersion"
testImplementation "org.json:json:$testOrgJsonVersion"
}
redacted {
redactAllDataClasses true
redactClassName true
}
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
}
}
ANSWER
Answered 2021-Dec-06 at 07:56My Gradle couldn't find the redacted-gradle-plugin but both of your classes compiles with this minimalistic build.gradle.kts:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
val kotlinVersion = "1.6.0"
kotlin("jvm") version kotlinVersion
}
repositories {
mavenCentral()
}
Also, while looking at the redacted page at https://github.com/StuStirling/redacted-compiler-plugin, it says "Kotlin compiler plugins are not a stable API", so at least do a "./gradlew clean"!
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install mockito
You can use mockito like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the mockito component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page