-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathAuditSecurityConfigurationTest.java
More file actions
79 lines (66 loc) · 2.47 KB
/
AuditSecurityConfigurationTest.java
File metadata and controls
79 lines (66 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.jdriven;
import com.jdriven.repo.Author;
import com.jdriven.repo.Blogpost;
import com.jdriven.repo.BlogpostRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.AutoConfigureTestEntityManager;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@AutoConfigureTestEntityManager
@Transactional
class AuditSecurityConfigurationTest {
@Autowired
private BlogpostRepository blogpostRepo;
@Autowired
private TestEntityManager em;
@BeforeEach
void setup() {
// Ensure active user can be looked up
Author author = new Author();
author.setName("test-user");
em.persist(author);
}
@Test
@WithMockUser("test-user")
void testSaveWhileLoggedInAsExistingUser() {
// Create and save a blogpost
Blogpost blogpost = new Blogpost();
blogpost.setTitle("Auditing Spring Data Entities");
Long id = blogpostRepo.save(blogpost).getId();
// Verify that author was set by JPA
Blogpost found = em.find(Blogpost.class, id);
assertThat(found.getCreatedBy()).hasValueSatisfying(a -> assertThat(a.getName()).isEqualTo("test-user"));
assertThat(found.getCreatedDate()).isNotEmpty();
}
@Test
@WithMockUser("non-existing-user")
void testSaveWhileLoggedInAsNonExistingUser() {
// Create and save a blogpost
Blogpost blogpost = new Blogpost();
blogpost.setTitle("Auditing Spring Data Entities");
Long id = blogpostRepo.save(blogpost).getId();
// Verify that author was not set by JPA
Blogpost found = em.find(Blogpost.class, id);
assertThat(found.getCreatedBy()).isEmpty();
assertThat(found.getCreatedDate()).isNotEmpty();
}
@Test
@WithAnonymousUser
void testSaveAsAnonymousUser() {
// Create and save a blogpost
Blogpost blogpost = new Blogpost();
blogpost.setTitle("Auditing Spring Data Entities");
Long id = blogpostRepo.save(blogpost).getId();
// Verify that author was not set by JPA
Blogpost found = em.find(Blogpost.class, id);
assertThat(found.getCreatedBy()).isEmpty();
assertThat(found.getCreatedDate()).isNotEmpty();
}
}