I use @ClassRule annotation to create container and start it:
@ClassRule
public static MySQLContainer mySqlContainer = new MySQLContainer("mysql:5.6.40");
protected EntityManager entityManager;
@Before
protected void setUp(Class... dbEntityClasses) throws Exception {
// override EMF settings
Map dataSourceProperties = new HashMap();
String connectionSource = mySqlContainer.getJdbcUrl()
+ "?user=" + mySqlContainer.getUsername()
+ "&password=" + mySqlContainer.getPassword();
dataSourceProperties.put("javax.persistence.jdbc.url", connectionSource);
dataSourceProperties.put("javax.persistence.jdbc.driver", mySqlContainer.getDriverClassName());
PersistenceFactory.getInstance().setProperties(dataSourceProperties);
// get db connection
entityManager = PersistenceFactory.getInstance().getEntityManager();
}
However i'm getting an exception later:
java.lang.IllegalStateException: Mapped port can only be obtained after the container is started
at org.testcontainers.shaded.com.google.common.base.Preconditions.checkState(Preconditions.java:174)
at org.testcontainers.containers.ContainerState.getMappedPort(ContainerState.java:89)
at org.testcontainers.containers.MySQLContainer.getJdbcUrl(MySQLContainer.java:56)
I've checked mySqlContainer.isRunning() returns false in mySqlContainer.getJdbcUrl() line (see code above).
Is it a bug or a feature?
Hi @4ntoine,
You sure you're using JUnit? :)
Also, don't you want to just use the JDBC-style support?
https://www.testcontainers.org/usage/database_containers.html#jdbc-url
/**
* Test for Dao
*/
public abstract class DaoTest {
@ClassRule
public static MySQLContainer mySqlContainer = new MySQLContainer("mysql:5.6.40");
protected EntityManager entityManager;
...
What makes you think i'm not?
Having both annotations and extending TestCase was the reason
@4ntoine I'm confused by how you solved it. Can you please give more details?
For anyone finding this in 2019 the problem is probably that you are confused if you are using Junit4 or Junit5.
Junit5 -> @TestContainer
Junit4 -> @Classrule
Check your imports.
If test is parametrized take a look at: https://github.com/testcontainers/testcontainers-java/issues/1774
Junit5 ->
@TestContainer
Junit5 -> @Container
Most helpful comment
For anyone finding this in 2019 the problem is probably that you are confused if you are using Junit4 or Junit5.
Junit5 ->
@TestContainerJunit4 ->
@ClassruleCheck your imports.