#ExpectedDatabase does not recognize deleted entity with MockMvc - spring-boot

I am having trouble using the #ExpectedDatabase annotation from springtestdbunit:
#SpringBootTest
#Transactional
#AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
#TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
TransactionDbUnitTestExecutionListener.class
})
#AutoConfigureMockMvc
class GroupControllerIntegrationTest {
#Autowired private MockMvc mvc;
#PersistenceContext private EntityManager entityManager;
#Test
#DatabaseSetup(value = "/createTwoGroups.xml")
#ExpectedDatabase(value = "/createSingleGroup.xml", table = "groups")
void givenGroups_deleteById_assert() throws Exception {
mvc.perform(delete("/groups/{id}", 1L))
.andDo(print())
.andExpect(status().is3xxRedirection())
.andExpect(redirectedUrl("/groups"))
.andExpect(model().hasNoErrors())
.andExpect(flash().attribute("message", "Gruppe erfolgreich gelöscht."));
// TODO: not working
// necessary due to:
// https://github.com/springtestdbunit/spring-test-dbunit/issues/75
entityManager.flush();
}
}
I receive
java.lang.Exception: org.dbunit.assertion.DbComparisonFailure[value (table=groups, row=0, col=id)expected:<1>but was:<2>]
As my comment in the integration test points out, the issue seems to be known. However, the suggested workaround with entityManager.flush() does not work with MockMvc.

Related

Jpa Auditing test null in getCreatedBy, and getLastModifiedBy

Hi I am trying to write unit test for Auditing
#DataJpaTest
#EnableJpaAuditing
#RunWith(SpringRunner.class)
#AutoConfigureEmbeddedDatabase(type=POSTGRES)
public class MyTestAuditor {
#Autowired
private TestEntityManager entityManager;
#Test
public void auditTest() throws InterruptedException {
final MyEntity testEntity = MyEntity.builder()
....
.build();
SLOEntity entity = entityManager.persistAndFlush(testEntity);
assertNotNull(testEntity.getCreatedOn());
assertNotNull(testEntity.getLastModifiedOn());
assertNotNull(testEntity.getCreatedBy());
assertNotNull(testEntity.getLastModifiedBy());
}
}
I pass first two assertion, the timestamp ones, but fail the username part. Is there anything I am missing here, thanks:)

Spring Boot Unit Testing MockMvc Null Body

I am having dificulties with using MockMvc.
Here I have simple Service and controller classes:
Service:
#Slf4j
#Service
public class EmployeeService {
//...
public Employee GetSample() {
//...
//filling Employee Entities
return new Employee(
"Harriet"
, "random"
, 25);
}
}
controller:
#RestController
#RequestMapping(value = "/info")
#RequiredArgsConstructor(onConstructor = #__(#Autowired))
#Validated
public class EmployeeController {
private final EmployeeService employeeService;
#PostMapping("/GetEmployee")
public ResponseEntity<Employee> GetEmployee() {
Employee employee = employeeService.GetSample();
return new ResponseEntity<>(employee, HttpStatus.OK);
}
}
Test:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class EmployeeTestCase {
private MockMvc mockMvc;
#InjectMocks
private EmployeeController EmployeeController;
#Mock
private EmployeeService employeeService;
#Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(employeeController).build();
}
#Test
public void getEmployee() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/info/GetEmployee")).andDo(print());
}
}
when I try to use MockMvc I get null body. It seems employee is null. But I didn't understand why.
I thought that when test uses perform, it should initialise employee and later on it should't be null.
I tried to cut the code as much as possible. I hope it is not long.
Note : also tried to use Mockito.when(employeeController.GetEmployee()).thenCallRealMethod();
The #SpringBootTest annotation loads the complete Spring application
context. That means you do not mock your layers
(Services/Controllers).
If you wanted to test specific layers of your application, you could look into test slice annotations offered by Springboot: https://docs.spring.io/spring-boot/docs/current/reference/html/test-auto-configuration.html
In contrast, a test slice annotation only loads beans required to test a particular layer. And because of this, we can avoid unnecessary mocking and side effects.
An example of a Test Slice is #WebMvcTest
#ExtendWith(SpringExtension.class)
#WebMvcTest(controllers = HelloController.class,
excludeFilters = {
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class)
}
)
public class HelloControllerTest {
#Autowired
private MockMvc mvc;
#Test
public void hello() throws Exception {
String hello = "hello";
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string(hello));
}
#Test
public void helloDto() throws Exception {
String name = "hello";
int amount = 1000;
mvc.perform(
get("/hello/dto")
.param("name", name)
.param("amount", String.valueOf(amount)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is(name)))
.andExpect(jsonPath("$.amount", is(amount)));
}
}
However if you really wanted to load up the SpringBoot Application context, say for an Integration Test, then you have a few options:
#SpringBootTest
#AutoConfigureMockMvc
public class TestingWebApplicationTest {
#Autowired
private MockMvc mockMvc;
#Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, World")));
}
}
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class AuctionControllerIntTest {
#Autowired
AuctionController controller;
#Autowired
ObjectMapper mapper;
MockMvc mockMvc;
#Before
public void setUp() throws Exception {
System.out.println("setup()...");
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
#Test
public void create_ValidAuction_ShouldAddNewAuction() throws Exception {
final Auction auction = new Auction(
"Standing Desk",
"Stand up desk to help you stretch your legs during the day.",
"Johnnie34",
350.00);
mockMvc.perform(post("/auctions")
.contentType(MediaType.APPLICATION_JSON)
.content(toJson(auction)))
.andExpect(status().isCreated());
}
}
Lets say you don't want to load up any layers at all, and you want to mock everything, such as for example a Unit Test:
#RunWith(MockitoJUnitRunner.class)
class DemoApplicationTest {
#Mock
private UserRepository userRepository;
private Demo noneAutoWiredDemoInstance;
#Test
public void testConstructorCreation() {
MockitoAnnotations.initMocks(this);
Mockito.when(userRepository.count()).thenReturn(0L);
noneAutoWiredDemoInstance = new Demo(userRepository);
Assertions.assertEquals("Count: 0", noneAutoWiredDemoInstance.toString());
}
}

MockMVC always Null

MockMvc is always null! i also tried other annotations like it is described at other questions but nothing works.
#ExtendWith(SpringExtension.class)
#WebMvcTest(controllers = HelpPageController.class)
public class HelpPageControllerTest {
#Autowired
private MockMvc mockMvc;
#Test
public void test() throws Exception {
//other code
ResultActions result = mockMvc.perform(MockMvcRequestBuilders.get("/help/manuals"));
//other code
}
You should add #AutoConfigureMockMvc annotation, so the MockMvc can be injected in your test class.

Testing dao layer with #DataJpaTest

I am writing unit testing using #DataJpaTest. Though it should do automatic rollback after every method, it is not doing that. Can you please help me with this.
This has 2 test cases written, ideally, test2 should return null, but it returns 1.
#RunWith(SpringRunner.class)
#DataJpaTest
public class EmployeeRepositoryTest {
#Autowired TestEntityManager em;
#Autowired EmployeeRepository rep;
// #Autowired EmployeeService service;
//Spring context loaded only once, reused by other methods
#Test
public void test1() {
// System.out.println(service); No such bean found
Employee e= new Employee();
e.setName("Payal");
em.persist(e);
em.flush();
Employee emp=rep.findByName("Payal");
assertNotNull(emp);
assertThat(emp.getId()).isGreaterThan(0);
}
#Test
public void test2() {
Employee emp=rep.findByName("Payal");
assertNull(emp);
}
}
Complete code can be found at:
https://github.com/payalbnsl/SpringUnitTestDemo/tree/master/src/test/java/com/example/demo/dao

How to mock JPA for Post method using mockito

Im trying to write the Unit test for a Create(Post) method which uses the JPA as DAO Layer .Im new to Mockito , hence insights needed .
1.EmployeeService .java
#Component("IEmployeeService ")
public class EmployeeService implements IInputService {
#Inject
EntityManagerFactory emf;
#PersistenceContext
EntityManager em;
public InputEntity create(InputEntity inputEntity) {
em = emf.createEntityManager();
try {
em.getTransaction().begin();
inputEntity.setLST_UPDTD_TS(new Date());
inputEntity.setLST_UPDTD_USER_ID(new String("USER1"));
em.persist(inputEntity);
em.getTransaction().commit();
} catch (PersistenceException e)
{
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
throw new WebApplicationException(e,Response.Status.INTERNAL_SERVER_ERROR);
}
finally {
em.close();
}
return inputEntity;
}
2.InputEntity.java is the Entity class with getters and setters for corresponding columns to employee age,salary ,etc .
Now if a Post method is called ,the create method in the EmployeeService class will be invoked .I have to write a unit test using mockito , and i m getting null-pointer , below is the test i wrote .
#Category(UnitTest.class)
#RunWith(MockitoJUnitRunner.class)
public class EmployeeServiceTest {
#Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
#Autowired
EmployeeService employeeService;
#Mock
InputEntity inputEntity;
#Mock
EntityManagerFactory emf;
#Mock
private EntityManager em;
#Mock
private EntityTransaction et;
#Rule
public ExpectedException expectedException = ExpectedException.none();
#Test
public void test_create_employee_success() throws Exception {
InputEntity expected = Mockito.mock(InputEntity .class);
Mockito.when(em.getTransaction()).thenReturn(et);
Mockito.when(emf.createEntityManager()).thenReturn(em);
Mockito.doReturn(expected).when(employeeService).create(inputEntityMock);
InputEntity actual = new InputEntity();
Mockito.doReturn(actual).when(employeeService).create(inputFileRoleValidationMock);
assertEquals(expected, actual);
}
You have a local mock expected, that you are attempting to use in an assertEquals(), but that will never work because assertEquals uses Object.equals, and Mockito hijacks equals for internal uses. A Mockito mock will never Object.equals anything except itself.
We had the similar problem of NullPointerException and it was because of the entity manager. After we updated the connection properties in setUp method, we could able to call the JPA.
You can try to set the connection properties something like this.
//declare emfactory
private static EntityManagerFactory emfactory;
private static EntityManager em;
#BeforeClass
public static void setUp() throws Exception{
Map<Object, Object> properties = new HashMap<Object, Object>();
properties.put("openjpa.ConnectionURL",
"jdbc:db2://yourserver:port/DBName");
properties.put("openjpa.ConnectionUserName", "username");
properties.put("openjpa.ConnectionPassword", "userpassword");
//set Schema
//set Driver Name
emfactory = Persistence.createEntityManagerFactory("PersistenceUnitName",
properties);
em = emfactory.createEntityManager();
Mockito.when(emf.createEntityManager()).thenReturn(em);
}
Plus you need to modify your test_create_employee_success() to make this working. You are mocking everything in this method, which you should not do. You can try something like this.
#Test
public void test_create_employee_success() throws Exception {
{
InputEntity inputEntity = new InputEntity();
employeeService.create(inputEntity);
}
You need following changes in the code:
1.Instead of
#Autowired
EmployeeService employeeService;
You can use:
#InjectMocks
private EmployeeService EmployeeService;
Also as you are mocking in the method - InputEntity expected = Mockito.mock(InputEntity .class); you dont need at this declaration at the class level unless it is used in some other methods.
Also you can get rid of the declaration -
InputEntity actual = new InputEntity();
You can not assert mocked object and object using new keyword for equality.
Clean unit test will look like this -
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class EmployeeServiceImplTest {
#Mock
private EntityManager em;
#Mock
private EntityManagerFactory emf;
#InjectMocks
private EmployeeService EmployeeService;
#Mock
private EntityTransaction et;
#Test
public void testCreate() throws Exception {
InputEntity expected = Mockito.mock(InputEntity.class);
Mockito.when(em.getTransaction()).thenReturn(et);
Mockito.when(emf.createEntityManager()).thenReturn(em);
EmployeeService.create(expected);
Mockito.verify(em, Mockito.times(1)).persist(expected);
}
}

Resources