Как использовать Mockito для пропуска вызова метода void - PullRequest
0 голосов
/ 16 сентября 2018

У меня есть контроллер REST, выставляющий конечную точку. При достижении этой конечной точки вызывается метод void, а затем этот метод отключается и отправляет файл в удаленное хранилище GitHub. Код работает прекрасно.

Моя проблема возникает при написании модульных тестов для класса. Я не хочу, чтобы действительный метод void вызывался (потому что он помещает файл в github). Я издевался над методом doNothing (), когда он вызывается, но по какой-то причине файл все еще отправляется. Куда я иду не так?

Ниже мой код:

// ApplicationController.java

@RestController
public class ApplicationController {

    @Autowired 
    GitService gitService;

    @GetMapping("/v1/whatevs")
    public String push_policy() throws IOException, GitAPIException {
        gitService.gitPush("Successfully pushed a fie to github...i think.");
        return "pushed the file to github.";
    }

}

// GitService.java

public interface GitService {

    public void gitPush(String fileContents) throws IOException, GitAPIException;

}

// GitServiceImpl.java

@Component
public class GitServiceImpl implements GitService {

    private static final Logger log = Logger.getLogger(GitServiceImpl.class.getName());

    @Override
    public void gitPush(String fileContents) throws IOException, GitAPIException {

        // prepare a new folder for the cloned repository
        File localPath = File.createTempFile(GIT_REPO, "");
        if (!localPath.delete()) {
            throw new IOException("Could not delete temporary file " + localPath);
        }

        // now clone repository
        System.out.println("Cloning from" + REMOTE_GIT_URL + "to " + localPath);

        try (Git result = Git.cloneRepository().setURI(REMOTE_GIT_URL).setDirectory(localPath)
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GIT_USER, GIT_PASSWORD)).call()) {
            // Note: the call() returns an opened repository already which needs to be
            // closed to avoid file handle leaks!
            Repository repository = result.getRepository();

            try (Git git = new Git(repository)) {

                // create the file
                Path path = Paths.get(String.format("%s/%s", localPath.getPath(), "someFileName"));
                byte[] strToBytes = fileContents.getBytes();
                Files.write(path, strToBytes);

                // add the file to the repo
                git.add().addFilepattern("someFileName").call();

                // commit the changes
                String commit_message = String
                        .format("[%s] Calico yaml file(s) generated by Astra Calico policy adaptor.", GIT_USER);

                git.commit().setMessage(commit_message).call();

                log.info("Committed file to repository at " + REMOTE_GIT_URL);

                // push the commits
                Iterable<PushResult> pushResults = git.push()
                        .setCredentialsProvider(new UsernamePasswordCredentialsProvider(GIT_USER, GIT_PASSWORD)).call();

                pushResults.forEach(pushResult -> log.info(pushResult.getMessages()));

            }
        } finally {
            // delete temp directory on disk
            FileUtils.deleteDirectory(localPath);
        }

    }

}

Мой тест. Это проходит, но метод gitService.gitpush (), который, как я думал, подвергался насмешке, передает файл в github.

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ApplicationControllerTest {

    @Autowired
    private MockMvc mockMvc;


    @Mock
    GitService gitService;

    //System under test
    @InjectMocks
    ApplicationController applicationController;


    public void setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(applicationController).build();
    }


    @Test
    public void controllerShouldReturnStatus200Ok() throws Exception {
        Mockito.doNothing().when(gitService).gitPush(Mockito.anyString());

        mockMvc.perform(

                MockMvcRequestBuilders.get("/v1/whatevs")


                ).andExpect(MockMvcResultMatchers.status().isOk());
    }

    @Test
    public void someTest() {
        assertTrue(true);
    }

}

Как я могу вообще не вызывать метод .gitPush ()? Я просто издеваюсь над сервисом неправильно?

1 Ответ

0 голосов
/ 16 сентября 2018
  1. Добавьте аннотацию @Before к вашему методу настройки в
  2. Добавьте это к вашему ранее методу MockitoAnnotations.initMocks (this).

Теперь должно работать

...