Skip to content

Commit

Permalink
setting up Mock annotation to be used (#259)
Browse files Browse the repository at this point in the history
* setting up Mock annotation to be used

* handled erroneous override of mocked bool
  • Loading branch information
AtillaColak authored Jul 31, 2023
1 parent 6162257 commit f3bdbe7
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package nl.tudelft.cse1110.andy.codechecker.checks;

import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Annotation;
import org.eclipse.jdt.core.dom.FieldDeclaration;


/**
* Checks whether the class was mocked via Mockito.mock(..).
Expand Down Expand Up @@ -38,6 +41,23 @@ public boolean visit(MethodInvocation mi) {
return super.visit(mi);
}

@Override
public boolean visit(FieldDeclaration fd) {
// added this if-check to avoid overriding classWasMocked erroneously.
if(!classWasMocked) {
boolean hasMockAnnotation = fd.modifiers().stream()
.anyMatch(m -> m instanceof Annotation &&
((Annotation) m).getTypeName().getFullyQualifiedName().equals("Mock"));

// If the field is annotated with @Mock, check if it's the class we are interested in
if (hasMockAnnotation) {
String className = fd.getType().toString();
classWasMocked = className.contains(classToBeMocked);
}
}
return super.visit(fd);
}


@Override
public boolean result() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
public class MockClassTest extends ChecksBaseTest {

@ParameterizedTest
@CsvSource({"List,true", "Set,true", "HashMap,false"})
@CsvSource({"List,true", "Set,true", "Queue,true", "Deque,true", "HashMap,false"})
void findMocks(String classToMock, boolean expectation) {
Check check = new MockClass(classToMock);
run("ManyMocks.java", check);
Expand Down
21 changes: 21 additions & 0 deletions andy/src/test/resources/codechecker/fixtures/ManyMocks.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.Queue;
import java.util.Deque;
import java.util.SortedSet;

import static org.mockito.Mockito.mock;
import org.mockito.MockitoAnnotations;
import org.junit.jupiter.api.BeforeEach;

/**
* Check if a specific class was mocked at least once, anywhere in
Expand All @@ -21,6 +26,21 @@
*/
public class ManyMocks {

// Mock with annotation
@Mock
Queue<String> mockedQueue;

@Mock
SortedSet<String> sortedSetMocked;

@Mock
Deque<String> mockedDQ;

@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
}

@Test
void t1() {
// full call to the static method
Expand All @@ -30,4 +50,5 @@ void t1() {
// no mock
HashMap<String, String> concreteHashMap = new HashMap<>();
}

}

0 comments on commit f3bdbe7

Please sign in to comment.