0

I have method:

public ReportBuilder addDiffs(List<String> diffs) {
    if (this.diffs == null) {
        this.diffs = new ArrayList<>();
    }
    this.diffs.addAll(diffs);
    return this;
}

And I want to make unit-test. As I khow it should be like:

@Test
public void ReportBuilderTest() {
    ReportBuilder builder = new ReportBuilder();
    List<String> list = new ArrayList<>();
    list.add("some string");

    builder.addDiffs(list);

    assertEquals(builder.getDiffs(), list));
}

It is example, but my class is inner service and i can't create getter for it. And diffs are private. How to make proper unit-test for this method? Maybe there is a problem with architecture?

petrov.aleksandr
  • 622
  • 1
  • 5
  • 24
  • Does this answer your question? [How do I test a private function or a class that has private methods, fields or inner classes?](https://stackoverflow.com/questions/34571/how-do-i-test-a-private-function-or-a-class-that-has-private-methods-fields-or) – Kent Shikama Dec 22 '19 at 11:18
  • 1
    I suppose it similar question, but as I khow using reflection in unit testing is very bad idea – petrov.aleksandr Dec 22 '19 at 11:21
  • See the second answer. – Kent Shikama Dec 22 '19 at 11:21
  • 2
    Unittests verify desired *public observable behavior*, not code, where "public observable behavior" is *return values* and *communication with dependencies*. Your method is expected to change the objects *internal state*. There is no *public observable behavior* to verify. Your code under test (CUT) should have other methods which change their behavior based on the objects state changed via this method. E.g.: There must be a method that somehow converts the list of "diffs" into something being returned by another method or passed to a *dependency* as Parameter. – Timothy Truckle Dec 22 '19 at 11:59

1 Answers1

0

You can use the Mockito framework. The object you are going to use can be built with dummy values using @mock Annotation. For more information on the different annotations, check the website https://site.mockito.org/

Kishore
  • 1
  • 1
  • I know about mockito, but in this case impossible to make mock of the list – petrov.aleksandr Dec 22 '19 at 11:26
  • •I'm not very much clear about the question. As per the code snippet provided, the arch should contain the ReportBuilder class as a 'Model', only then you can access its getter and setter methods. •If you want to check if the values are same then use Assertions.assertThat(builder.getDiffs()).containsExactly("sone string"); • if you want to check the length use assertEquals(builder.getDiffs().size, list.size)); – Kishore Dec 22 '19 at 11:42