'Cannot be accessed from outside package error when using @Builder annotation in Post api unit test in spring Boot

I am writing a unit test to test a Post API create Team in spring ,

@WebMvcTest(TeamController.class)
public class TeamControllerTest {

    @Autowired
    MockMvc mockMvc;
    @Autowired
    ObjectMapper mapper;

    @MockBean
    TeamRepository teamRepository;

    // ... Test methods TBA

  @Test
  public void createTeam_success() throws Exception {
    Team team = Team.builder()
        .teamName("BARCA")
        .employeeIds(Collections.singleton("620268fa6a391035457478df"))
        .build();

    Mockito.when(teamRepository.save(team)).thenReturn(team);

    MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.post("/api/v1/team")
        .contentType(MediaType.APPLICATION_JSON)
        .accept(MediaType.APPLICATION_JSON)
        .content(this.mapper.writeValueAsString(team));

    mockMvc.perform(mockRequest)
        .andExpect(status().isOk())
        .andExpect(jsonPath("$", notNullValue()))
        .andExpect((ResultMatcher) jsonPath("$.teamName", is("BARCA")));
  }

}

Here is my Team.java class , It also has a set of strings from employees which are going to be part of the team

@Getter
@Setter
@Builder
public class Team extends AuditEntity {
  private String teamName;
  private Set<String> employeeIds = new LinkedHashSet<>();

}

But the main problem is that when I am using the @Builder annotation in Team class. It is giving me an error in my TeamService where I have declared the method createnewTeam.

public class TeamService {

  private final TeamTranslator translator;
  private final TeamRepository teamRepository;
  private final EmployeeRepository employeeRepository;

  public TeamDTO createnewTeam(TeamDTO teamDTO) {
    log.info("Creating New Team");
    Team teamEntity = translator.toEntity(teamDTO,new Team());
    teamRepository.save(teamEntity);
    return translator.toDTO(teamEntity);
  }

translator.toEntity(teamDTO,new Team()); the error is in this

error : 'Team(java.lang.String, java.util.Set<java.lang.String>)' is not public in 'com.hitech.solutions.web.domain.employee.Team'. Cannot be accessed from outside package**


Solution 1:[1]

The constructor generated by @Builder is package private. I suppose your TeamService class is not located in the same package as the Team class. More info here: https://projectlombok.org/features/Builder and here: https://projectlombok.org/features/constructor

To solve your problem, just add @NoArgsConstructor and @AllArgsConstructor to your Team class in order to generate a public default no-args constructor and a public constructor for all fields.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alex