0

Entity class

@Getter
@NoArgsConstructor
@Entity
public class Posts {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(length = 500, nullable = false)
    private String title;
    
    @Column(columnDefinition = "TEXT", nullable = false)
    private String content;
    
    private String author;
    
    @Builder
    public Posts(String title, String content, String author) {
        this.title = title;
        this.content = content;
        this.author = author;
    }
}

Test code

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class PostsAPIControllerTest {
    @LocalServerPort
    private int port;
    
    @Autowired
    private TestRestTemplate restTemplate;
    
    @Autowired
    private PostsRepository postsRepository; // PostsRepository extends JpaRepository<Posts, Long>
    
    @After
    public void tearDown() throws Exception {
        postsRepository.deleteAll();
    }
    
    @Test
    public void posts_save() throws Exception {
        String title = "title";
        String content = "content";
        
        PostsSaveRequestDTO requestDTO = PostsSaveRequestDTO.builder()
                                                            .title(title)
                                                            .content(content)
                                                            .author("author")
                                                            .build();
        
        String url = "http://localhost:" + port + "/api/v1/posts";
        ResponseEntity<Long> responseEntity = restTemplate.postForEntity(url, requestDTO, Long.class);
        
        assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(responseEntity.getBody()).isGreaterThan(0L);
        
        List<Posts> all = postsRepository.findAll();
        
        assertThat(all.get(0).getTitle()).isEqualTo(title);
        assertThat(all.get(0).getContent()).isEqualTo(content);
    }
}

Controller

@RequiredArgsConstructor
@RestController
public class PostsAPIController {
    private final PostsService postsService;
    
    @PostMapping("/api/v1/posts")
    public Long save(@RequestBody PostsSaveRequestDTO requestDTO) {
        return postsService.save(requestDTO);
    }
    
    @PutMapping("/api/v1/posts/{id}")
    public Long update(@PathVariable Long id, @RequestBody PostsUpdateRequestDTO requestDTO) {
        return postsService.update(id, requestDTO);
    }
    
    @GetMapping("/api/v1/posts/{id}")
    public PostsResponseDTO findById(@PathVariable Long id) {
        return postsService.findById(id);
    }
}

I made a sample Spring Boot test code that updates DB, but test fails with following error message if I execute the code. I already defined spring.security.user.name and spring.security.user.password to application.properties file.

What is the problem? I tried to reload after removing testImplementation 'org.springframework.security:spring-security-test' from build.gradle, but nothing has changed.

Expecting:
 <401 UNAUTHORIZED>
to be equal to:
 <200 OK>
but was not.
Romil Patel
  • 12,879
  • 7
  • 47
  • 76
EnDelt64
  • 1,270
  • 3
  • 24
  • 31
  • 2
    Could you show you security configuration and you controller? If this is not related to authentication, it could also be related to CSRF (see [this question](https://stackoverflow.com/q/48985293/13688761)). – Miguel Alorda Jul 04 '20 at 19:20
  • @m-alorda I added controller code. What exactly do you mean by 'security settings'? I just set `spring.security.user.name` and `spring.security.user.password` in application.properties. – EnDelt64 Jul 05 '20 at 01:19
  • You need to add credentials to the Header - Refer https://www.baeldung.com/spring-boot-testresttemplate – Thirumal Jul 05 '20 at 03:31

1 Answers1

0

There are multiple ways to mock the security using @WithMockUser, @WithAnonymousUser, @WithUserDetails, @WithSecurityContext. You can use these annotations with @Test method You may change the roles as required in the project. You may like to explore more details here

@Test
@WithMockUser(username="admin",roles="ADMIN")
public void posts_save() throws Exception {
    String title = "title";
    String content = "content";
    
    PostsSaveRequestDTO requestDTO = PostsSaveRequestDTO.builder()
                                                        .title(title)
                                                        .content(content)
                                                        .author("author")
                                                        .build();
    
    String url = "http://localhost:" + port + "/api/v1/posts";
    ResponseEntity<Long> responseEntity = restTemplate.postForEntity(url, requestDTO, Long.class);
    
    assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(responseEntity.getBody()).isGreaterThan(0L);
    
    List<Posts> all = postsRepository.findAll();
    
    assertThat(all.get(0).getTitle()).isEqualTo(title);
    assertThat(all.get(0).getContent()).isEqualTo(content);
Romil Patel
  • 12,879
  • 7
  • 47
  • 76