Skip to content

Improve unit testing - #660

Merged
kingthorin merged 1 commit into
datafaker-net:mainfrom
kingthorin:more-tests
Jan 31, 2023
Merged

kingthorin merged 1 commit into
datafaker-net:mainfrom
kingthorin:more-tests

Conversation

@kingthorin

@kingthorin kingthorin commented Jan 30, 2023 •

Copy link
Copy Markdown
Collaborator
  • AbstractBasicProviderTest > Added so that applicable tests could extend it in order to ensure that the values the providers return are actually within the expected list.
  • various > Updated Unit Test classes to leverage the new abstract.
  • Overwatch > moved to the videogame package.

This is in follow-up to: #657.

Signed-off-by: kingthorin kingthorin@users.noreply.github.com

@what-the-diff

what-the-diff Bot commented Jan 30, 2023

Copy link
Copy Markdown
  • The testEquipment method was changed to use the simpleListTest helper.
  • The locations, animals and states methods were all updated in a similar way as above.
  • A new method called simpleListTest was added which takes two parameters:

@kingthorin

Copy link
Copy Markdown
Collaborator Author

This is in follow-up to: #657. Please don't merge this yet, I'm just submitting to get initial feedback, then I'll extended to further providers/properties.

@bodiam are you happy with how this is looking? Is there anything you'd want done differently?

@codecov-commenter

codecov-commenter commented Jan 30, 2023 •

Copy link
Copy Markdown

Codecov Report

Merging #660 (95679ea) into main (3457e4e) will increase coverage by 0.03%.
The diff coverage is n/a.

📣 This organization is not using Codecov’s GitHub App Integration. We recommend you install it so Codecov can continue to function properly for your repositories. Learn more

@@             Coverage Diff              @@
##               main     #660      +/-   ##
============================================
+ Coverage     92.77%   92.81%   +0.03%     
- Complexity     2634     2635       +1     
============================================
  Files           283      283              
  Lines          5426     5426              
  Branches        589      589              
============================================
+ Hits           5034     5036       +2     
- Misses          238      241       +3     
+ Partials        154      149       -5     
Impacted Files Coverage Δ
.../main/java/net/datafaker/service/FakerContext.java 83.58% <0.00%> (-1.50%) ⬇️
...c/main/java/net/datafaker/providers/base/Text.java 77.96% <0.00%> (-0.85%) ⬇️
...ker/idnumbers/pt/br/IdNumberGeneratorPtBrUtil.java 96.29% <0.00%> (+3.70%) ⬆️
...net/datafaker/internal/helper/SingletonLocale.java 85.00% <0.00%> (+10.00%) ⬆️

📣 We’re building smart automated test selection to slash your CI/CD build times. Learn more

@snuyanzin

Copy link
Copy Markdown
Collaborator

what do you think about parameterized test on BaseFakerTest level which could be annotated with @MethodSource pointing to abstract method providing key and supplier.
All other tests classes should just implement this method

@kingthorin

kingthorin commented Jan 30, 2023 •

Copy link
Copy Markdown
Collaborator Author

Can you provide params to a @MethodSource definition? I thought the annotation was simply @MethodSource("myParamGenerator")

Or maybe I'm misunderstanding your vision.

@kingthorin

kingthorin commented Jan 30, 2023 •

Copy link
Copy Markdown
Collaborator Author

It seems @MethodSource methods are expected to be static, which an abstract method can't be. (Or I'm still not following along 😉)

Here's what I tried. Click the triangle/control to the left to expand
package net.datafaker.providers.base;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

abstract class AbstractProviderTest extends BaseFakerTest<BaseFaker> {

    @SuppressWarnings("unchecked")
    protected List<String> getBaseList(String key) {
        return (List<String>) faker.fakeValuesService().fetchObject(key, faker.getContext());
    }

    abstract Stream<Arguments> simpleTestArgs();

    /**
     * Ensures that the supplied method actually returns a value in the expected list.
     * 
     * @param method the method from which the test value will be obtained.
     * @param key the YAML key from which the list of actual items should be retrieved.
     */
    @ParameterizedTest
    @MethodSource("simpleTestArgs")
    protected void simpleTest(Supplier<?> method, String key) {
        System.out.println("Method: " + method == null);
        System.out.println("Key: " + key == null);
        // Given
        List<String> actual = getBaseList(key);
        // When
        String item = (String) method.get();
        // Then
        assertThat(actual).anyMatch(item::equals);
    }

}
package net.datafaker.providers.base;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.provider.Arguments;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.stream.Stream;

class ApplianceTest extends AbstractProviderTest {

    @Test
    void brand() {
        assertThat(faker.appliance().brand()).matches("[A-Za-z .-]+");
    }

    @Override
    Stream<Arguments> simpleTestArgs() {
        return Stream.of(
                Arguments.of(faker.appliance().equipment(), "appliance.equipment"));
    }
}

@snuyanzin

snuyanzin commented Jan 30, 2023 •

Copy link
Copy Markdown
Collaborator

it could be non-static however in this case BaseFakerTest should be annotated as @TestInstance(TestInstance.Lifecycle.PER_CLASS) as below

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class BaseFakerTest<T extends BaseFaker> {
...

   @ParameterizedTest(name = "{0}")
    @MethodSource("simpleTestArgs")
    protected void simpleListTest(TestSpec testSpec) {
        // Given
        List<String> actual = getBaseList(testSpec.key);
        // When
        String item = (String) testSpec.supplier.get();
        // Then
        assertThat(actual).anyMatch(item::equals);
    }

    protected abstract Collection<TestSpec> simpleTestArgs();

    protected static class TestSpec {
        private final Supplier<?> supplier;
        private final String key;
        private TestSpec(Supplier<?> supplier, String key) {
            this.supplier = supplier;
            this.key = key;
        }

        public static TestSpec of(Supplier<?> supplier, String key) {
            return new TestSpec(supplier, key);
        }

        @Override
        public String toString() {
            // The result of this toString will be used by IDE in test report
            return "Key: " + key;
        }
    }
...

It's better to use pojo since there are some java compiliation issues for the case like Arguments.of(() -> faker.appliance().equipment(), "appliance.equipment")
.

On child tests it could look like that e.g. just one method instead of 3 in AustraliaTest

class AustraliaTest extends BaseFakerTest<BaseFaker> {

    @Override
    protected Collection<TestSpec> simpleTestArgs() {
        return Arrays.asList(TestSpec.of(() -> faker.australia().locations(), "australia.locations"),
            TestSpec.of(() -> faker.australia().animals(), "australia.animals"),
            TestSpec.of(() -> faker.australia().states(), "australia.states"));
    }
}

@kingthorin

Copy link
Copy Markdown
Collaborator Author

Cool thanks!!

I’ll tweak the names too, I know all the simple* weren’t great. I was just trying to get a functioning model setup.

@kingthorin

Copy link
Copy Markdown
Collaborator Author

I had to separate it into another class so that it could be extended by only those classes where it was applicable. But it's working nicely so I'm moving ahead. I'm about a third done the base provider list. Will get this updated later this evening.

@kingthorin

Copy link
Copy Markdown
Collaborator Author

The LocalityTest failure seems to be related to having added @TestInstance(TestInstance.Lifecycle.PER_CLASS) which I guess means that there's some state that was shared previously that is no longer.

@kingthorin

kingthorin commented Jan 31, 2023 •

Copy link
Copy Markdown
Collaborator Author

Relocated it to the new Abastract which resolved the issue.

@kingthorin kingthorin changed the title Improve unit testing - WIP Improve unit testing Jan 31, 2023
@snuyanzin

Copy link
Copy Markdown
Collaborator

Thanks, it looks great.
In general lgtm.
I added a couple of tiny comments

- AbstractBasicProviderTest > Added so that applicable tests could
extend it in order to ensure that the values the providers return are
actually within the expected list.
- various > Updated Unit Test classes to leverage the new abstract.
- Overwatch > moved to the videogame package.

Signed-off-by: kingthorin <kingthorin@users.noreply.github.com>
@bodiam

bodiam commented Jan 31, 2023

Copy link
Copy Markdown
Contributor

This PR looks @kingthorin . If you think it's okay, I'm happy if you want to merge it yourself.

@bodiam
bodiam self-requested a review January 31, 2023 12:09
@bodiam

bodiam commented Jan 31, 2023 •

Copy link
Copy Markdown
Contributor

PS: I'm not sure if it's too much to ask, but there's a ProviderGenerator class, which creates Provider classes and tests to match them. Would it make sense to update this class too?

@kingthorin

Copy link
Copy Markdown
Collaborator Author

I’ll have a look at that. If it’s quick I’ll add it here, otherwise I’ll tackle it in another PR.

@bodiam

bodiam commented Jan 31, 2023

Copy link
Copy Markdown
Contributor

I’ll have a look at that. If it’s quick I’ll add it here, otherwise I’ll tackle it in another PR.

No need to tackle it, I can do it, and I'm not even sure we still need the class since we now have Providers for almost all yml files, except for the gaming ones, the are slightly more complex to auto generate.

@kingthorin

kingthorin commented Jan 31, 2023 •

Copy link
Copy Markdown
Collaborator Author

@bodiam There's one pending review. Reading back through the log: you self requested a review after you suggested merging? 😉 I’m going to guess stray click but want to be sure before I go ahead with it. (Thanks for the collab invite BTW)

@snuyanzin
snuyanzin self-requested a review January 31, 2023 13:48
@bodiam

bodiam commented Jan 31, 2023

Copy link
Copy Markdown
Contributor

@bodiam There's one pending review. Reading back through the log: you self requested a review after you suggested merging? 😉 I’m going to guess stray click but want to be sure before I go ahead with it. (Thanks for the collab invite BTW)

Ah, I was in two minds here, I wasn't sure if we required a review of not, and then I was reviewing, and got distracted :) So let's call it a stray click indeed :)

@kingthorin
kingthorin merged commit 206f855 into datafaker-net:main Jan 31, 2023
@kingthorin
kingthorin deleted the more-tests branch January 31, 2023 20:31
@kingthorin

Copy link
Copy Markdown
Collaborator Author

Yay 🎉

@bodiam

bodiam commented Jan 31, 2023

Copy link
Copy Markdown
Contributor

Woohoo! Nice! 🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants