The model tests are omitted here because they are essentially the same as in the impure section. In contrast to the tests on the impure service, we will now write unit tests for our routes.
This means that we will be able to test our routing logic without spinning up a database.
Test repository
To be able to test our routes, we will have to implement a TestRepository first, which we will use instead of the concrete implementation that is wired to a database.
xxxxxxxxxx
class TestRepository[F[_]: Effect](data: Seq[Product]) extends Repository[F]{
override def loadProduct(id: ProductId) = {
data.find(_.id === id) match {
case None => Seq.empty.pure[F]
case Some(p) =>
val ns = p.names.toNonEmptyList.toList.to[Seq]
ns.map(n => (p.id, n.lang, n.name)).pure[F]
}
}
override def loadProducts() = {
Stream.empty
}
override def saveProduct(p: Product): F[Int] =
data.find(_.id === p.id).fold(0.pure[F])(_ => 1.pure[F])
override def updateProduct(p: Product): F[Int] =
data.find(_.id === p.id).fold(0.pure[F])(_ => 1.pure[F])
}
xxxxxxxxxx
UNIT TESTING is a software testing where individual
units or components of a software are tested.
The purpose is to validate that each unit of the
software performs as designed.
Unit testing involves testing individual units or components of your application in isolation. In Spring Boot, you can use JUnit or any other testing framework to write unit tests for your application. You can use mock objects to simulate dependencies, so that you can test your code without relying on external systems. Unit tests can help you to catch bugs early in the development process and ensure that your code is functioning as expected.
Here’s an example of a simple unit test for a Spring Boot application using JUnit and Mockito:
Suppose we have a UserService class that depends on a UserRepository interface:
xxxxxxxxxx
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JavaTestContext.class)
public class DependencyInjectionJavaContextExamples {
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/TestContext.xml" })
public class TodoBusinessTest {
xxxxxxxxxx
import inc_dec # The code to test
import unittest # The test framework
class Test_TestIncrementDecrement(unittest.TestCase):
def test_increment(self):
self.assertEqual(inc_dec.increment(3), 4)
# This test is designed to fail for demonstration purposes.
def test_decrement(self):
self.assertEqual(inc_dec.decrement(3), 4)
if __name__ == '__main__':
unittest.main()
xxxxxxxxxx
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@Mock
private UserRepository userRepository;
@Test
public void testGetUsernameById() {
// Create a mock user
User user = new User();
user.setId(1);
user.setUsername("johndoe");
// Set up the mock UserRepository to return the mock user
when(userRepository.findUserById(1)).thenReturn(user);
// Create the UserService and call the method we want to test
UserService userService = new UserService(userRepository);
String username = userService.getUsernameById(1);
// Verify that the method returned the correct username
assertEquals("johndoe", username);
}
}
Base class for unit tests
Testing Product fromDatabase
Testing a JSON codec
Testing decoding garbage input
Testing invalid input values
Testing valid input
Testing included fields
Decoding encoded JSON
More tests
Testing Translation fromUnsafe
Base class for unit tests
To avoid repeating the construction of our unit test classes, we will implement a base class for tests, which is quite simple.
xxxxxxxxxx
abstract class BaseSpec extends WordSpec
with MustMatchers with ScalaCheckPropertyChecks {}