Created
November 22, 2022 06:38
-
-
Save NizarETH/a374ededbc3c893931e4db2c96825525 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dans Unit Test | |
============================================ | |
Database | |
============================================ | |
public class Database { | |
public boolean isAvailable() { | |
// currently not implemented, as this is just demo used in a software test | |
return false; | |
} | |
public int getUniqueId() { | |
return 42; | |
} | |
} | |
============================================ | |
Service | |
============================================ | |
public class Service { | |
private Database database; | |
public Service(Database database) { | |
this.database = database; | |
} | |
public boolean query(String query) { | |
return database.isAvailable(); | |
} | |
@Override | |
public String toString() { | |
return "Using database with id: " + String.valueOf(database.getUniqueId()); | |
} | |
} | |
============================================ | |
ExampleUnitTest | |
============================================ | |
@RunWith(MockitoJUnitRunner.class) | |
public class ExampleUnitTest { | |
@Mock | |
Database databaseMock; | |
@Test | |
public void testQuery() { | |
assertNotNull(databaseMock); | |
when(databaseMock.isAvailable()).thenReturn(true); | |
Service t = new Service(databaseMock); | |
boolean check = t.query("* from t"); | |
assertThat(check, equalTo(true)); | |
} | |
@Test | |
public void ensureMockitoReturnsTheConfiguredValue() { | |
// define return value for method getUniqueId() | |
when(databaseMock.getUniqueId()).thenReturn(42); | |
Service service = new Service(databaseMock); | |
// use mock in test.... | |
assertEquals(service.toString(), "Using database with id: 42"); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment