I am trying to write integration tests for Quarkus using Mockito, but I fail using Argument captor.
Here is a minimal (not) working example :
#QuarkusTest
#ExtendWith(MockitoExtension.class)
public class SimpleTest {
#Captor
private ArgumentCaptor<Context> contextArgumentCaptor;
#Test
public void testOne() {
System.out.println(contextArgumentCaptor);
}
}
contextArgumentCaptor is "null".
If I remove #QuarkusTest, contextArgumentCaptor is created.
It also works with #QuarkusTest and direct Argument creator :
#QuarkusTest
public class ConfigTest {
private ArgumentCaptor<Context> contextArgumentCaptor;
#BeforeEach
public void setup() {
contextArgumentCaptor = ArgumentCaptor.forClass(Context.class);
}
#Test
public void givenValidCloudEvent_whenHandleHandoverFunction_ThenHandoverStarted() {
System.out.println(contextArgumentCaptor);
}
}
So it is really the combinaison of #QuarkusTest with #Captor that doesn't work.
Any idea?
Yes, using #QuarkusTest along with the #Captor will not work correctly. You must create the captor yourself
Related
I am going to test my controller using springsecurity.
#PostMapping("/xx")
public String xx(Authentication auth){
String userId = (String)auth.getPrincipal();
....
}
I have no idea how to mock Authentication object. Or is there other way to deal with it?
My test shown below
public class MyControllerTest{
#Autowired
private XxController xxController;
private MockMvc mockMvc;
#Before
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(xxController).build();
}
#Test
public void xxtestMethod() throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(/xx))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
}
For basic auth, after trying different ways to do it, I found this worked for me :
MockMvcRequestBuilders
.post(urlEndpoint)
.principal(new MyAuthentication())
Notice that MyAuthentication class implements the Authentication interface
Below is my code snippet. This is giving me compilation error, as env.getProperty will return String. How do I get integer value. Interger.ParseInt is not working.
when(this.env.getProperty("NeededIntegerValue")).thenReturn(15);
Below is my test class
public class MyclassTest {
Myclass myObj=new Myclass();
#Mock Environment env=Mockito.mock(Environment.class);
#Before
public void init() {
when(this.env.getProperty("StringKey1")).thenReturn("Stringvalue");
when(this.env.getProperty("StringKey2")).thenReturn(intValue);
myObj.setEnvironment(this.env);
}
#Test
public void testTenantIdentifierCutomerTypeCUSTOMER_ACCOUNT() {
assertEquals("Expecteddata",myObj.testMethod(new StringBuilder(inputData),anotherData).toString);
}
}
Below is the Method needs to be tested
public StringBuilder testMethod(StringBuilder inputData, String anotherData)
{
if (anotherData.equals(env.getProperty("StringKey1"))) {
inputData=inputData.append(","+arrayOfInputData[Integer.parseInt(env.getProperty("intValue"))]);
}
}
First, you should mock your env, this way:
when(this.env.getProperty("StringKey1")).thenReturn("StringValue");
when(this.env.getProperty("StringKey2")).thenReturn("StringRepresentationOfYourInt");
Second, pay attention to the method itself, should be
arrayOfInputData[Integer.parseInt(env.getProperty("StringKey2"))
not
arrayOfInputData[Integer.parseInt(env.getProperty("intValue"))
Instead of
myObj.setEnvironment(this.env); in init() method try:
#InjectMocks
Myclass myObj = new Myclass();
Also remove assignment for
#Mock Environment env=Mockito.mock(Environment.class);
it should look
#Mock Environment env;
Normally, when I use #SpringBootTest I get the full context of beans. I can the #Autowire all kinds of beans that are available after the application has started.
Now, in the scope of spring-integration-test libary, the #SpringIntegrationTest does not do this.
As the testing module promises, you can use
#Autowired
private MockIntegrationContext mockIntegrationContext;
However, after inspecting the bean map on that instance, I found out there are no beans!
Example test:
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#SpringIntegrationTest
public class AppTest {
#Autowired
private MockIntegrationContext mockIntegrationContext;
#Test
public void contextLoads() {
// put breakpoint to inspect field
System.out.println(mockIntegrationContext);
}
}
When I however run the following code, I get a complete context:
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#SpringBootTest
public class App2Test {
#Autowired
private ListableBeanFactory beanFactory;
#Test
public void contextLoads() {
Assert.isTrue(beanFactory.getBeanDefinitionCount() > 0)
}
}
Why is that? How can I achieve a similar result with spring-integration-test?
Reading materials: https://docs.spring.io/spring-integration/docs/current/reference/html/testing.html
They are independent annotations; you need both.
EDIT
This works fine for me:
#RunWith(SpringRunner.class)
#SpringBootTest
#SpringIntegrationTest
public class So52297757ApplicationTests {
#Autowired
private MockIntegrationContext mockIntegrationContext;
#Autowired
private String foo;
#Test
public void contextLoads() {
System.out.println(foo);
System.out.println(mockIntegrationContext);
}
}
and
#SpringBootApplication
public class So52297757Application {
public static void main(String[] args) {
SpringApplication.run(So52297757Application.class, args);
}
#Bean
public String foo() {
return "foo";
}
}
and
foo
org.springframework.integration.test.context.MockIntegrationContext#1de5f0ef
I use PowerMockito mock a class instance that contains private method. And I want to verify private method return value is correct, So how to use PowerMock invoke private method and get return value?
This is demo:
class Demo {
public publicMethod1ReturnClass publicMethod1() {
// do something...
}
private privateMethod1ReturnClass privateMethod1() {
// do something
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(Demo.class)
class DemoTest {
#Test
public void test() throws Exception {
Demo demo = PowerMockito.spy(new Demo());
privateMethod1ReturnClass result = demo.privateMethod1();
}
}
You can do it using Whitebox like this,
privateMethod1ReturnClass s = Whitebox.invokeMethod(demo, "privateMethod1");
assertEquals(s, "yourExpectedResult");
Not duplicate of: Inherited test class from generic base is ignored in MSTest
In my case, the test classes are in the same namespace/assembly.
When unittesting classes which have a lot in common, I would like to use a base test class with a generic parameter. I have boiled the problem down to the following, where my base test method is not being executed, but ONLY in the generic case.
Non-generic: Base test method is EXECUTED:
[TestClass]
public class DerivedTestClass : BaseUnitTest
{
protected override string ReturnMeSomething(object obj)
{
return "test1" + obj.ToString();
}
[TestMethod]
public void derived_test()
{
// This is executed
}
}
[TestClass]
public abstract class BaseUnitTest
{
[TestMethod]
public void base_test()
{
// This is executed
}
protected abstract string ReturnMeSomething(object obj);
}
Generic: Base test method in generic base class is NOT EXECUTED:
[TestClass]
public class DerivedTestClass : BaseUnitTest<string>
{
protected override string ReturnMeSomething(string s)
{
return "test1" + s;
}
[TestMethod]
public void derived_test()
{
// This is executed
}
}
[TestClass]
public abstract class BaseUnitTest<T>
{
[TestMethod]
public void base_test()
{
// This is NOT executed
}
protected abstract string ReturnMeSomething(T t);
}
Can anyone tell me the reason for this?
After a few days, this suddenly works (!!). If anyone ever experiences this same, odd behavior, please write a comment here. I would suggest anyone to reboot and clean+rebuild everything and try again.