I've been learning about tests lately but this is the first test were I've had to pass a variable in a function that I'm mocking. I've written a similar test were the only difference is that i use an ArgumentMatcher in this test because the testInput.validate() needs 3 Strings to pass with it. I don't know this stuff very well so I'm sorry if the terminology is off.
Here is the code i'm trying to test:
@Component public class RequestHandler { private static Gson gson = new Gson(); private final UserRepository userRepository; private final TestInput testInput; @Autowired public RequestHandler(UserRepository userRepository, TestInput testInput) { this.userRepository = UserRepository; this.testInput = testInput; } public String addUser(String username, String email, String password) { if (testInput.validate(username, email, password) && !(userRepository.findById(email).isPresent())) { User user = new User(username, email, password); userRepository.save(user); return gson.toJson(user); } else { return gson.toJson("error"); } } } And here is my test:
public class RequestHandlerTest { UserRepository userRepository = Mockito.mock(UserRepository.class); TestInput testInput = Mockito.mock(TestInput.class); RequestHandler requestHandler = new RequestHandler(userRepository, testInput); String test = ArgumentMatchers.anyString(); @Test public void addUserTest() { Mockito.when(testInput.validate(test, test, test)).thenReturn(true, false); Mockito.when(userRepository.findById(test).isPresent()).thenReturn(false, true); String jsonUser = new Gson().toJson(new User("username123","[email protected]","12344321")); String jsonError = new Gson().toJson("error"); System.out.println("addUser Test1"); assertEquals(jsonUser, requestHandler.addUser("username123","[email protected]","12344321")); System.out.println("addUser Test2"); assertEquals(jsonError, requestHandler.addUser("username123","[email protected]","12344321")); } } I had a bunch of errors with this code and when I changed the ArgumentMatchers.anyString() to just ArgumentMatchers.any() I had 1 error instead of like 5.