Текущая версия Spring Boot: 3.4.2 Testng Версия: 7.10.2 Spring Test: 6.2.2 (от Parent Spring Depedency) < /p>
После весны 3.2.0 мы получали предупреждение о том, что @mockbean и @spybean установились, но мы продолжали использовать их. С весны 3.4.0 они отмечены для удаления, поэтому мы перенесли их в @mockitobean и @mockityspybean соответственно. На Local - все работает, они работают, но на Дженкинсе мы видим ошибку, которую объект передал, когда () нуль. Пробовал много решений, не повезло, вот сценарий использования (упрощенное). Для сохранения кода проекта I Refactored, но сохранив основную цель использования:
иерархия: mytest
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootTest(classes = { Application.class },
properties = { "spring.main.allow-bean-definition-overriding=true" },
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ComponentScan({ "com.blabla.blabla" })
@TestConfiguration
public @interface DefaultTestConfig {
}
< /code>
@DefaultTestConfig
public abstract class BaseAPITest extends AbstractTestNGSpringContextTests {
@LocalServerPort
private int port;
@BeforeSuite(alwaysRun = true)
public final void prepareTestContext() throws Exception {
log.info("Preparing test context");
super.springTestContextPrepareTestInstance();
}
}
< /code>
@SuppressWarnings("unchecked")
public class SomeBaseAPITest extends BaseAPITest {
@MockitoSpyBean(reset = MockReset.NONE)
private SomeCsvServiceImpl someCsvService;
@BeforeSuite(alwaysRun = true, dependsOnMethods = "prepareTestContext")
protected void prepareMocks() {
doAnswer(invocationOnMock -> TestService.translate(invocationOnMock.getArgument(1)))
.when(morningstarCsvService)
.translate(any(), any(), any(), any(), any());
}
}
< /code>
public class MyTest extends SomeBaseAPITest {
@Test
void myTest() {
var response = given()
.get("http://blablabla.com");
assertTrue(response != null);
}
}
< /code>
The error:
18:11:09 [INFO]
18:11:09 [INFO] Results:
18:11:09 [INFO]
18:11:09 [ERROR] Failures:
18:11:09 [ERROR] SomeBaseAPITest.prepareMocks:83 » NullInsteadOfMock
18:11:09 Argument passed to when() is null!
18:11:09 Example of correct stubbing:
18:11:09 doThrow(new RuntimeException()).when(mock).someMethod();
18:11:09 Also, if you use @Mock annotation don't miss openMocks()
18:11:09 [INFO]
18:11:09 [ERROR] Tests run: 357, Failures: 1, Errors: 0, Skipped: 356
< /code>
The error means the code here:
doAnswer(invocationOnMock -> TestService.translate(invocationOnMock.getArgument(1)))
.when(morningstarCsvService)
.translate(any(), any(), any(), any(), any());
< /code>
Why do we use such hierarchy of classes? To run the context once and reuse context in mocks configuration. Why 2 methods for beforeSuite ? The one method loads the context (because the context is by default loaded in beforeClass, but in beforeSuite it is manually forced to load). The second one deligates creating mocks (in the real example there are more classes and more methods, here is an abstraction).
Again: it is working on local, and isn't on jenknins. Jenkins can see some error, and maybe he is correct. When hovering the mouse on the
@MockitoSpyBean(reset = MockReset.NONE)
private SomeCsvServiceImpl someCsvService;
< /code>
it is showing, that someCsvService is not assigned (means the value is not initialized). When there was @MockBean annotation, there wasn't such warning. Hope to get help from communite!!!
Simplified jenkins pipeline:
import hudson.util.Secret
node('maven38'){
try {
stage('Checkout code') {
git(branch: '$BRANCH', credentialsId: 'GITHUB', url: 'https://NDA')
}
stage('Run Test') {
withCredentials([usernamePassword(credentialsId: 'DEVOPS', passwordVariable: 'NEXUS_PASS', usernameVariable: 'NEXUS_USER')]) {
sh ''' mvn --settings ${WORKSPACE}/settings.xml -Dspring.profiles.active=test -Dsurefire.suiteXmlFiles=src/test/resources/suites/api-testng.xml clean test '''
}
}
} catch (e) {
echo 'This will run only if failed' throw e
} finally { ...
< /code>
Tried changing private to protected Tried to move field to the test classes Tried to change the configuration with different combinations Cannot migrate to the @MockBean to test as it is marked for removal (of course I can suppress removal warnings, but that's not a solution)
Expect not to see error with null instead of object in mock configuration on Jenkins
Подробнее здесь: https://stackoverflow.com/questions/795 ... ring-3-4-0
Spring Boot Tests не работает на Дженкинсе, но работают на местном уровне с весны 3.4.0 ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Spring Boot Tests не работает на Дженкинсе, но работают на местном уровне с весны 3.4.0
Anonymous » » в форуме JAVA - 0 Ответы
- 32 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Spring Boot Tests не работает на Дженкинсе, но работают на местном уровне с весны 3.4.0
Anonymous » » в форуме JAVA - 0 Ответы
- 40 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Spring Boot Tests не работает на Дженкинсе, но работают на местном уровне с весны 3.4.0
Anonymous » » в форуме JAVA - 0 Ответы
- 24 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Spring Boot Tests не работает на Дженкинсе, но работают на местном уровне с весны 3.4.0
Anonymous » » в форуме JAVA - 0 Ответы
- 208 Просмотры
-
Последнее сообщение Anonymous
-