Skip to content

Commit 167d296

Browse files
Merge pull request eugenp#14183 from thibaultfaure/article/BAEL-6587
BAEL-6587 Code for the Mockito Exception article
2 parents 8e3eabc + cd67755 commit 167d296

File tree

4 files changed

+64
-3
lines changed

4 files changed

+64
-3
lines changed

testing-modules/mockito-2/pom.xml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<project xmlns="http://maven.apache.org/POM/4.0.0"
3-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
2+
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xmlns="http://maven.apache.org/POM/4.0.0"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
55
<modelVersion>4.0.0</modelVersion>
66
<artifactId>mockito-2</artifactId>
77

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.baeldung.wantedbutnotinvocked;
2+
3+
class Helper {
4+
5+
String getBaeldungString() {
6+
return "Baeldung";
7+
}
8+
9+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.baeldung.wantedbutnotinvocked;
2+
3+
class Main {
4+
5+
Helper helper = new Helper();
6+
7+
String methodUnderTest(int i) {
8+
if (i > 5) {
9+
return helper.getBaeldungString();
10+
}
11+
return "Hello";
12+
}
13+
14+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.baeldung.wantedbutnotinvocked;
2+
3+
import org.junit.jupiter.api.BeforeEach;
4+
import org.junit.jupiter.api.Test;
5+
import org.mockito.InjectMocks;
6+
import org.mockito.Mock;
7+
import org.mockito.Mockito;
8+
import org.mockito.MockitoAnnotations;
9+
10+
class MainUnitTest {
11+
12+
@Mock
13+
Helper helper;
14+
15+
@InjectMocks
16+
Main main = new Main();
17+
18+
@BeforeEach
19+
void setUp() {
20+
MockitoAnnotations.openMocks(this);
21+
}
22+
23+
@Test
24+
void givenValueUpperThan5_WhenMethodUnderTest_ThenDelegatesToHelperClass() {
25+
main.methodUnderTest(7);
26+
Mockito.verify(helper)
27+
.getBaeldungString();
28+
}
29+
30+
// Uncomment the next line to see the error
31+
// @Test
32+
void givenValueLowerThan5_WhenMethodUnderTest_ThenDelegatesToGetBaeldungString() {
33+
main.methodUnderTest(3);
34+
Mockito.verify(helper)
35+
.getBaeldungString();
36+
}
37+
38+
}

0 commit comments

Comments
 (0)