dimanche 1 décembre 2019

Why do mock annotations not mock/inject a repository?

I am using mockito to test a controller. That controller uses a repository that connects to database. I want to mock userRepository and inject it in usercontroller, but when I run the test a NullPointerException is thrown at when(userRepository.addUser(anyString(), anyString())).thenReturn(true); in the test as you can see below. Also when I removed this line to see whether mockMvc also gived this error and indeed it did just that.

This I think the problem causer is the MockitoAnnotations.initMocks(this); that it somehow doesn't enable the annotations.

I did some research about why this is happening on Google but with none of the solutions solved this problem and I don't know why this is not working.

My Controller that I want to test:

@RestController
public class UserController {

    @Autowired
    private transient userRepository userRepository;

    @PostMapping("/user/add")
    public ResponseEntity<?> addUser(@RequestBody User user) {
        String firstname = user.getUsername();
        String lastname = user.getLastName();

        boolean added = userRepository.addUser(username, lastname );

        if(added){
            return new ResponseEntity<>(true, HttpStatus.OK);
        }

        return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

My test so far:

@RunWith(SpringRunner.class)
class UserControllerTest {

    private MockMvc mockMvc;

    @MockBean
    private UserRepository userRepository;

    @InjectMocks
    private UserController userController;

    @BeforeEach
    public void init() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders
                .standaloneSetup(userController)
                .build();
    }

    @Test
    void testAddUserToDb() throws Exception {
        User user = new User();
        User.setFirstName("first");
        User.setLastName("last");

        Gson gson = new Gson();
        String request = gson.toJson(user);

        //HERE I GET NULLPOINTEREXCEPTION
        when(userRepository.addUser(anyString(), anyString())).thenReturn(true);

        mockMvc.perform(post("user/add")
                .contentType(MediaType.APPLICATION_JSON).content(request))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));


        verify(userRepository, times(1)).addUser(anyString(), anyString());
        verifyNoMoreInteractions(userRepository);
    }

My user repository:

@Repository
public class UserRepository {

    @Autowired
    private transient JdbcTemplate jdbcTemplate;

    public boolean addUser(String firstName, String lastName){
        boolean added = false;

        String ADD_USER = "INSERT INTO Users(username, lastname) VALUES(?, ?)";

        //execute sql query and retrieve result set
        int rowsHit = jdbcTemplate.update(ADD_USER, firstName, lastName);

        if (rowsHit == 1) {
            added = true;
        }

        return added;
    }

my build.gradle does contain testImplementation 'org.springframework.boot:spring-boot-starter-test' and testCompile "org.mockito:mockito-core:1.+"

Aucun commentaire:

Enregistrer un commentaire