BAEL-6587 Code for the Mockito Exception article

This commit is contained in:
thibault.faure 2023-06-05 12:57:33 +02:00
parent c341505b45
commit 1e4c42c6d1
4 changed files with 64 additions and 3 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>mockito-2</artifactId>

View File

@ -0,0 +1,9 @@
package com.baeldung.wantedbutnotinvocked;
class Helper {
String getBaeldungString() {
return "Baeldung";
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.wantedbutnotinvocked;
class Main {
Helper helper = new Helper();
String methodUnderTest(int i) {
if (i > 5) {
return helper.getBaeldungString();
}
return "Hello";
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.wantedbutnotinvocked;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
class MainUnitTest {
@Mock
Helper helper;
@InjectMocks
Main main = new Main();
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void givenValueUpperThan5_WhenMethodUnderTest_ThenDelegatesToHelperClass() {
main.methodUnderTest(7);
Mockito.verify(helper)
.getBaeldungString();
}
// Uncomment the next line to see the error
// @Test
void givenValueLowerThan5_WhenMethodUnderTest_ThenDelegatesToGetBaeldungString() {
main.methodUnderTest(3);
Mockito.verify(helper)
.getBaeldungString();
}
}