From 432c96cf08b77879aa8af4f0aebdb36e759926ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Mon, 18 Mar 2024 17:19:31 +0800 Subject: [PATCH 01/38] add specific type to any() --- .../template/context/MockitoMockBuilder.java | 9 +++++++++ .../impl/InnerStaticClassWithMemberTest.java | 2 +- .../test/com/example/services/impl/FooTest.java | 2 +- .../com/example/services/impl/FooTest.groovy | 2 +- .../test/com/example/services/impl/FooTest.java | 2 +- .../com/example/services/impl/FooTest.groovy | 2 +- .../test/com/example/services/impl/FooTest.java | 2 +- .../com/example/services/impl/FooTest.groovy | 2 +- .../com/example/services/impl/FooTest.java | 2 +- .../com/example/services/impl/FooTest.groovy | 2 +- .../com/example/services/impl/FooTest.java | 2 +- .../test/com/example/services/impl/FooTest.java | 2 +- .../com/example/services/impl/FooTest.groovy | 2 +- .../test/com/example/services/impl/FooTest.java | 12 ++++++------ .../com/example/services/impl/FooTest.groovy | 12 ++++++------ .../test/com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.groovy | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- 19 files changed, 41 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index 177bc2b2..3ec211cd 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -236,9 +236,18 @@ private String deductMatcherTypeMethod(Param param, Language language) { if (language != Language.Scala) { matcherType += "()"; } + // add specific type to any() + if( matcherType.equals("any()")){ + matcherType = mockCanonicalName(param.getType().getCanonicalName()); + } return matcherType; } + String mockCanonicalName(String canonicalName) { + int lastIndex = canonicalName.lastIndexOf('.'); + return lastIndex != -1 ? "any("+canonicalName.substring(lastIndex + 1)+".class)" : "any()"; + } + /** * true - if should stub tested method * @param testMethod method being tested diff --git a/testData/testMeAdditionalAction/innerStaticClassWithMember/test/com/example/services/impl/InnerStaticClassWithMemberTest.java b/testData/testMeAdditionalAction/innerStaticClassWithMember/test/com/example/services/impl/InnerStaticClassWithMemberTest.java index edcaa83a..326ccd4e 100644 --- a/testData/testMeAdditionalAction/innerStaticClassWithMember/test/com/example/services/impl/InnerStaticClassWithMemberTest.java +++ b/testData/testMeAdditionalAction/innerStaticClassWithMember/test/com/example/services/impl/InnerStaticClassWithMemberTest.java @@ -27,7 +27,7 @@ public void setUp() { @Test public void testMethodOfInnerClass() throws Exception { - when(innerFooFighter.fight(any())).thenReturn("fightResponse"); + when(innerFooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); String result = innerStaticClassWithMember.methodOfInnerClass(new Fire()); Assert.assertEquals("replaceMeWithExpectedResult", result); diff --git a/testData/testMeGenerator/inheritance/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/inheritance/test/com/example/services/impl/FooTest.java index 8e0ea2c7..73af8848 100644 --- a/testData/testMeGenerator/inheritance/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/inheritance/test/com/example/services/impl/FooTest.java @@ -25,7 +25,7 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any())).thenReturn("fightResponse"); + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); String result = foo.fight(new com.example.foes.Fire(), "foeName"); Assert.assertEquals("replaceMeWithExpectedResult", result); diff --git a/testData/testMeGenerator/inheritance/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/inheritance/testGroovy/com/example/services/impl/FooTest.groovy index 159bf082..95da7602 100644 --- a/testData/testMeGenerator/inheritance/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/inheritance/testGroovy/com/example/services/impl/FooTest.groovy @@ -23,7 +23,7 @@ class FooTest { @Test void testFight() { - when(fooFighter.fight(any())).thenReturn("fightResponse") + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse") java.lang.String result = foo.fight(new com.example.foes.Fire(), "foeName") assert result == "replaceMeWithExpectedResult" diff --git a/testData/testMeGenerator/inheritanceIgnored/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/inheritanceIgnored/test/com/example/services/impl/FooTest.java index df4c5cf8..5d4ae249 100644 --- a/testData/testMeGenerator/inheritanceIgnored/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/inheritanceIgnored/test/com/example/services/impl/FooTest.java @@ -25,7 +25,7 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any())).thenReturn("fightResponse"); + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); String result = foo.fight(new com.example.foes.Fire(), "foeName"); Assert.assertEquals("replaceMeWithExpectedResult", result); diff --git a/testData/testMeGenerator/inheritanceIgnored/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/inheritanceIgnored/testGroovy/com/example/services/impl/FooTest.groovy index 297957e9..bdc059b8 100644 --- a/testData/testMeGenerator/inheritanceIgnored/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/inheritanceIgnored/testGroovy/com/example/services/impl/FooTest.groovy @@ -23,7 +23,7 @@ class FooTest { @Test void testFight() { - when(fooFighter.fight(any())).thenReturn("fightResponse") + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse") java.lang.String result = foo.fight(new com.example.foes.Fire(), "foeName") assert result == "replaceMeWithExpectedResult" diff --git a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java index 5cddbb56..58e98b82 100644 --- a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java @@ -35,7 +35,7 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(fooFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy index 6fd7bf1c..95e27223 100644 --- a/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy @@ -33,7 +33,7 @@ class FooTest { @Test void testFight() { - when(fooFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0, fear: new Fear(), ice: new Ice())) + when(fooFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0, fear: new Fear(), ice: new Ice())) when(result.get()).thenReturn(0) String result = foo.fight(new Fire(), "foeName") diff --git a/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java index 1f917260..63aa281c 100644 --- a/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java @@ -35,7 +35,7 @@ void setUp() { @Test void testFight() { - when(fooFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(fooFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy index 976e0685..a2734a86 100644 --- a/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy @@ -31,7 +31,7 @@ class FooTest extends Specification { def "test fight"() { given: - when(fooFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0, fear: new Fear(), ice: new Ice())) + when(fooFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0, fear: new Fear(), ice: new Ice())) when(result.get()).thenReturn(0) when: diff --git a/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java index 0e389647..707ae6ce 100644 --- a/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java @@ -35,7 +35,7 @@ public void setUp() { @Test public void testFight() { - when(fooFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(fooFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/paramsConstructors/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/paramsConstructors/test/com/example/services/impl/FooTest.java index 32aa422e..47815b8d 100644 --- a/testData/testMeGenerator/paramsConstructors/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/paramsConstructors/test/com/example/services/impl/FooTest.java @@ -37,7 +37,7 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any())).thenReturn("fightResponse"); + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); BigBean result = foo.fight(new Fire(), List.of("foeName"), new BigBean(new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), null, "ifYourInDaHood"), new Many("family", "members", "only"), new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), null, "ifYourInDaHood")), new BeanThere(new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), new BigBean(null, new Many("family", "members", "only"), null), "ifYourInDaHood"), new Many("family", "members", "only"))); Assert.assertEquals(new BigBean(new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), null, "ifYourInDaHood"), new Many("family", "members", "only"), new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), null, "ifYourInDaHood")), result); diff --git a/testData/testMeGenerator/paramsConstructors/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/paramsConstructors/testGroovy/com/example/services/impl/FooTest.groovy index 51934713..df6dc6e3 100644 --- a/testData/testMeGenerator/paramsConstructors/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/paramsConstructors/testGroovy/com/example/services/impl/FooTest.groovy @@ -29,7 +29,7 @@ class FooTest { @Test void testFight() { - when(fooFighter.fight(any())).thenReturn("fightResponse") + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse") BigBean result = foo.fight(new Fire(), ["foeName"], new BigBean(new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), null, "ifYourInDaHood"), new Many("family", "members", "only"), new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), null, "ifYourInDaHood")), new BeanThere(new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), new BigBean(null, new Many("family", "members", "only"), null), "ifYourInDaHood"), new Many("family", "members", "only"))) assert result == new BigBean(new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), null, "ifYourInDaHood"), new Many("family", "members", "only"), new DoneThat(0, "aDay", new Many("family", "members", "only"), new GregorianCalendar(2016, Calendar.JANUARY, 11, 22, 45).getTime(), null, "ifYourInDaHood")) diff --git a/testData/testMeGenerator/variousFieldTypes/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/variousFieldTypes/test/com/example/services/impl/FooTest.java index a8c9c531..56563c8c 100644 --- a/testData/testMeGenerator/variousFieldTypes/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/variousFieldTypes/test/com/example/services/impl/FooTest.java @@ -45,12 +45,12 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any())).thenReturn("fightResponse"); - when(fooFighterProtected.fight(any())).thenReturn("fightResponse"); - when(fooFighterDefault.fight(any())).thenReturn("fightResponse"); - when(fooFighterPublic.fight(any())).thenReturn("fightResponse"); - when(fooFighterFinal.fight(any())).thenReturn("fightResponse"); - when(fooFighterStatic.fight(any())).thenReturn("fightResponse"); + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterProtected.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterDefault.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterPublic.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterFinal.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterStatic.fight(any(Fire.class))).thenReturn("fightResponse"); when(innerOfPublicInnerClass.methodOfInnerClass()).thenReturn(new Foo().new PublicInnerClass().new InnerOfPublicInnerClass()); String result = foo.fight(new com.example.foes.Fire(), "foeName"); diff --git a/testData/testMeGenerator/variousFieldTypes/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/variousFieldTypes/testGroovy/com/example/services/impl/FooTest.groovy index 96e848e4..5f9d523c 100644 --- a/testData/testMeGenerator/variousFieldTypes/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/variousFieldTypes/testGroovy/com/example/services/impl/FooTest.groovy @@ -41,12 +41,12 @@ class FooTest { @Test void testFight() { - when(fooFighter.fight(any())).thenReturn("fightResponse") - when(fooFighterProtected.fight(any())).thenReturn("fightResponse") - when(fooFighterDefault.fight(any())).thenReturn("fightResponse") - when(fooFighterPublic.fight(any())).thenReturn("fightResponse") - when(fooFighterFinal.fight(any())).thenReturn("fightResponse") - when(fooFighterStatic.fight(any())).thenReturn("fightResponse") + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(fooFighterProtected.fight(any(Fire.class))).thenReturn("fightResponse") + when(fooFighterDefault.fight(any(Fire.class))).thenReturn("fightResponse") + when(fooFighterPublic.fight(any(Fire.class))).thenReturn("fightResponse") + when(fooFighterFinal.fight(any(Fire.class))).thenReturn("fightResponse") + when(fooFighterStatic.fight(any(Fire.class))).thenReturn("fightResponse") when(innerOfPublicInnerClass.methodOfInnerClass()).thenReturn(new com.example.services.impl.Foo.PublicInnerClass.InnerOfPublicInnerClass(new com.example.services.impl.Foo.PublicInnerClass(new com.example.services.impl.Foo()))) java.lang.String result = foo.fight(new com.example.foes.Fire(), "foeName") diff --git a/testData/testMeGenerator/verifyMethodCall/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/verifyMethodCall/test/com/example/services/impl/FooTest.java index a3db85f5..d169e6e6 100644 --- a/testData/testMeGenerator/verifyMethodCall/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/verifyMethodCall/test/com/example/services/impl/FooTest.java @@ -32,8 +32,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/verifyMethodCall/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/verifyMethodCall/testGroovy/com/example/services/impl/FooTest.groovy index cd787760..1d764a22 100644 --- a/testData/testMeGenerator/verifyMethodCall/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/verifyMethodCall/testGroovy/com/example/services/impl/FooTest.groovy @@ -28,8 +28,8 @@ class FooTest { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) String result = foo.fight(new Fire(), "foeName") diff --git a/testData/testMeGenerator/verifyMethodCall/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/verifyMethodCall/testJunit5/com/example/services/impl/FooTest.java index 8d0c0725..3a7788c0 100644 --- a/testData/testMeGenerator/verifyMethodCall/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/verifyMethodCall/testJunit5/com/example/services/impl/FooTest.java @@ -32,8 +32,8 @@ void setUp() { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/verifyMethodCall/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/verifyMethodCall/testTestNg/com/example/services/impl/FooTest.java index 25c95234..84e3fb27 100644 --- a/testData/testMeGenerator/verifyMethodCall/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/verifyMethodCall/testTestNg/com/example/services/impl/FooTest.java @@ -32,8 +32,8 @@ public void setUp() { @Test public void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); From 19dc74a93abcdd5e2b3afc83717c9b2ae97940db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Tue, 19 Mar 2024 09:53:13 +0800 Subject: [PATCH 02/38] add specific type to any() --- .../testme/intellij/template/context/MockitoMockBuilder.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index 3ec211cd..44657d5a 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -238,12 +238,12 @@ private String deductMatcherTypeMethod(Param param, Language language) { } // add specific type to any() if( matcherType.equals("any()")){ - matcherType = mockCanonicalName(param.getType().getCanonicalName()); + matcherType = addSpecificType(param.getType().getCanonicalName()); } return matcherType; } - String mockCanonicalName(String canonicalName) { + String addSpecificType(String canonicalName) { int lastIndex = canonicalName.lastIndexOf('.'); return lastIndex != -1 ? "any("+canonicalName.substring(lastIndex + 1)+".class)" : "any()"; } From 3e7b2dcccc71104505454d7c1968739fe87e0e5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Wed, 20 Mar 2024 14:05:46 +0800 Subject: [PATCH 03/38] add specific type to any() --- .../test/com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.groovy | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.groovy | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../test/com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.groovy | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.groovy | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../test/com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.groovy | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.groovy | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.java | 4 ++-- .../com/example/services/impl/FooTest.java | 12 ++++++------ 19 files changed, 42 insertions(+), 42 deletions(-) diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDependencyInjection/test/com/example/services/impl/FooTest.java index fd88aa53..273f9784 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/test/com/example/services/impl/FooTest.java @@ -33,8 +33,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDependencyInjection/testGroovy/com/example/services/impl/FooTest.groovy index a8c52b38..72035cca 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testGroovy/com/example/services/impl/FooTest.groovy @@ -29,8 +29,8 @@ class FooTest { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) String result = foo.fight(new Fire(), "foeName") diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDependencyInjection/testJunit5/com/example/services/impl/FooTest.java index d66ace41..fe1ec6e8 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testJunit5/com/example/services/impl/FooTest.java @@ -33,8 +33,8 @@ void setUp() { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDependencyInjection/testPowerMock/com/example/services/impl/FooTest.java index c403a509..9d5454f5 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testPowerMock/com/example/services/impl/FooTest.java @@ -42,8 +42,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); verify(techFighter).initSelfArming(anyString()); diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDependencyInjection/testSpock/com/example/services/impl/FooTest.groovy index 71653bfd..640be037 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testSpock/com/example/services/impl/FooTest.groovy @@ -27,8 +27,8 @@ class FooTest extends Specification { def "test fight"() { given: - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) when: diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDependencyInjection/testTestNg/com/example/services/impl/FooTest.java index 9669ff74..d452d686 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testTestNg/com/example/services/impl/FooTest.java @@ -33,8 +33,8 @@ public void setUp() { @Test public void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithCtor/test/com/example/services/impl/FooTest.java index a3db85f5..d169e6e6 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/test/com/example/services/impl/FooTest.java @@ -32,8 +32,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDiWithCtor/testGroovy/com/example/services/impl/FooTest.groovy index cd787760..1d764a22 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/testGroovy/com/example/services/impl/FooTest.groovy @@ -28,8 +28,8 @@ class FooTest { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) String result = foo.fight(new Fire(), "foeName") diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithCtor/testJunit5/com/example/services/impl/FooTest.java index 8d0c0725..3a7788c0 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/testJunit5/com/example/services/impl/FooTest.java @@ -32,8 +32,8 @@ void setUp() { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDiWithCtor/testSpock/com/example/services/impl/FooTest.groovy index 62274d8e..2f89cc4c 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/testSpock/com/example/services/impl/FooTest.groovy @@ -26,8 +26,8 @@ class FooTest extends Specification { def "test fight"() { given: - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) when: diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithCtor/testTestNg/com/example/services/impl/FooTest.java index 25c95234..84e3fb27 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/testTestNg/com/example/services/impl/FooTest.java @@ -32,8 +32,8 @@ public void setUp() { @Test public void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithSetter/test/com/example/services/impl/FooTest.java index fd88aa53..273f9784 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/test/com/example/services/impl/FooTest.java @@ -33,8 +33,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDiWithSetter/testGroovy/com/example/services/impl/FooTest.groovy index a8c52b38..72035cca 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/testGroovy/com/example/services/impl/FooTest.groovy @@ -29,8 +29,8 @@ class FooTest { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) String result = foo.fight(new Fire(), "foeName") diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithSetter/testJunit5/com/example/services/impl/FooTest.java index d66ace41..fe1ec6e8 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/testJunit5/com/example/services/impl/FooTest.java @@ -33,8 +33,8 @@ void setUp() { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDiWithSetter/testSpock/com/example/services/impl/FooTest.groovy index 71653bfd..640be037 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/testSpock/com/example/services/impl/FooTest.groovy @@ -27,8 +27,8 @@ class FooTest extends Specification { def "test fight"() { given: - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) when: diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithSetter/testTestNg/com/example/services/impl/FooTest.java index 9669ff74..d452d686 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/testTestNg/com/example/services/impl/FooTest.java @@ -33,8 +33,8 @@ public void setUp() { @Test public void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/renderInternalMethodCallStubs/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/renderInternalMethodCallStubs/testPowerMock/com/example/services/impl/FooTest.java index e6c6746b..0ff8229b 100644 --- a/testData/testMeGenerator/renderInternalMethodCallStubs/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/renderInternalMethodCallStubs/testPowerMock/com/example/services/impl/FooTest.java @@ -42,8 +42,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); Foo fooSpy = spy(foo); doReturn("thinkResponse").when(fooSpy, "think", anyString()); diff --git a/testData/testMeGenerator/renderInternalMethodCallStubsIgnored/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/renderInternalMethodCallStubsIgnored/testPowerMock/com/example/services/impl/FooTest.java index c403a509..9d5454f5 100644 --- a/testData/testMeGenerator/renderInternalMethodCallStubsIgnored/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/renderInternalMethodCallStubsIgnored/testPowerMock/com/example/services/impl/FooTest.java @@ -42,8 +42,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); verify(techFighter).initSelfArming(anyString()); diff --git a/testData/testMeGenerator/variousFieldTypes/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/variousFieldTypes/testPowerMock/com/example/services/impl/FooTest.java index 6c7d2a40..37d7dfd5 100644 --- a/testData/testMeGenerator/variousFieldTypes/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/variousFieldTypes/testPowerMock/com/example/services/impl/FooTest.java @@ -57,12 +57,12 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any())).thenReturn("fightResponse"); - when(fooFighterProtected.fight(any())).thenReturn("fightResponse"); - when(fooFighterDefault.fight(any())).thenReturn("fightResponse"); - when(fooFighterPublic.fight(any())).thenReturn("fightResponse"); - when(fooFighterFinal.fight(any())).thenReturn("fightResponse"); - when(fooFighterStatic.fight(any())).thenReturn("fightResponse"); + when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterProtected.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterDefault.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterPublic.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterFinal.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighterStatic.fight(any(Fire.class))).thenReturn("fightResponse"); when(innerOfPublicInnerClass.methodOfInnerClass()).thenReturn(new Foo().new PublicInnerClass().new InnerOfPublicInnerClass()); String result = foo.fight(new com.example.foes.Fire(), "foeName"); verify(publicInnerClass).methodOfInnerClass(); From 2edd29f9bbf16aa64660aeecfed8fc777701fe50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Wed, 20 Mar 2024 15:37:09 +0800 Subject: [PATCH 04/38] add specific type to any() --- .../intellij/template/context/MockitoMockBuilder.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index ed390e99..4708e107 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -2,6 +2,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.weirddev.testme.intellij.generator.TestBuilderUtil; +import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -242,7 +243,7 @@ private String deductMatcherTypeMethod(Param param, Language language) { } // add specific type to any() if( matcherType.equals("any()")){ - matcherType = addSpecificType(param.getType().getCanonicalName()); + matcherType = addSpecificType(param.getType().getName()); } return matcherType; } @@ -253,9 +254,8 @@ public boolean shouldStub(Method testMethod, List testedClassFields) { return callsMockMethod(testMethod, testedClassFields, Method::hasReturn, null); } - String addSpecificType(String canonicalName) { - int lastIndex = canonicalName.lastIndexOf('.'); - return lastIndex != -1 ? "any("+canonicalName.substring(lastIndex + 1)+".class)" : "any()"; + String addSpecificType(String typeName) { + return StringUtils.isNotEmpty(typeName) ? "any("+typeName+".class)" : "any()"; } /** * true - if should stub tested method From 0efb82cf24c9c1546f1ce1f5b9ba968c206fba2e Mon Sep 17 00:00:00 2001 From: Yaron Yamin Date: Wed, 20 Mar 2024 18:13:51 +0200 Subject: [PATCH 05/38] test generator: avoid mocking field that is initialized inline and it's name matches typical logger naming patterns (to reduce impact since currently not searching for overrides by ctor and static initializers --- .../intellij/template/context/Field.java | 5 ++++ .../template/context/MockitoMockBuilder.java | 25 ++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/Field.java b/src/main/java/com/weirddev/testme/intellij/template/context/Field.java index 3f5158f6..0f4674b7 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/Field.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/Field.java @@ -45,6 +45,10 @@ public class Field { * true if field has setter in tested class */ @Getter private final boolean hasSetter; + /** + * true if field is set to a value on declaration + */ + @Getter private final boolean isInitializedInline; /** * name given to field @@ -61,6 +65,7 @@ public Field(PsiField psiField, PsiClass srcClass, TypeDictionary typeDictionary overridden = isOverriddenInChild(psiField, srcClass); isFinal = psiField.getModifierList() != null && psiField.getModifierList().hasExplicitModifier(PsiModifier.FINAL); isStatic = psiField.getModifierList() != null && psiField.getModifierList().hasExplicitModifier(PsiModifier.STATIC); + isInitializedInline = typeDictionary!=null && typeDictionary.isTestSubject(srcClass) && psiField.hasInitializer();//hasInitializer - expensive test - call only for test subject (consider moving to a new type - ExtendedField - for usage in test subject } /** diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index a76d771c..c0b28292 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -20,6 +20,7 @@ public class MockitoMockBuilder implements MockBuilder{ private static final Logger LOG = Logger.getInstance(MockitoMockBuilder.class.getName()); public static final Map TYPE_TO_ARG_MATCHERS; private static final Pattern SEMVER_PATTERN = Pattern.compile("^(\\d*)\\.(\\d*)\\.*"); + public static final Pattern LOGGER_PATTERN = Pattern.compile("(?i).*log.*"); static { TYPE_TO_ARG_MATCHERS = new HashMap<>(); @@ -119,14 +120,36 @@ public boolean isMockable(Field field) { @SuppressWarnings("unused") @Override public boolean isMockable(Field field, Type testedClass) { + //todo extract common logic and reflect in powermock as well final boolean isMockable = !field.getType().isPrimitive() && !isWrapperType(field.getType()) && (!field.getType().isFinal() || isMockitoMockMakerInlineOn) && !field.isOverridden() && !field.getType().isArray() && !field.getType().isEnum() - && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass); + && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass) && !isInitInline(field); LOG.debug("field " + field.getType().getCanonicalName() + " " + field.getName() + " is mockable:" + isMockable); return isMockable; } + private static boolean isInitInline(Field field) { + //for now, avoid applying on all such fields since it's hard to deduct if default value overridden in ctor. settling for typical logger initialization pattern + //todo try to deduct if init in static block + return field.isInitializedInline() && !field.isHasSetter() && LOGGER_PATTERN.matcher(field.getName()).matches(); + } + + /** + * Avoid mocking a field if all these conditions are met: + * class has DI annotation + * field has no direct DI annotation + * field does not have a setter + * there is no class constructor. + * @param field field + * @param testedClass testedClass + * @return true if field meet conditions above + */ + private boolean isNotInjectedInDiClass(Field field, Type testedClass) { + return testedClass != null && testedClass.isAnnotatedByDI() && !field.isAnnotatedByDI() && !field.isHasSetter() + && !testedClass.hasConstructor(); + } + /** * true - if argument can be mocked given the provided default types */ From 246dfdde5920ac8830da0c30fe412ce8499a2834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Mon, 25 Mar 2024 14:03:47 +0800 Subject: [PATCH 06/38] add user check dialog --- .../generator/TestMeGeneratorTestBase.java | 20 +- .../intellij/action/CreateTestMeAction.java | 56 +++-- .../intellij/generator/TestMeGenerator.java | 20 +- .../generator/TestTemplateContextBuilder.java | 2 + .../template/context/MockBuilder.java | 5 + .../template/context/MockitoMockBuilder.java | 12 ++ .../template/context/PowerMockBuilder.java | 14 ++ .../context/TestMeTemplateParams.java | 13 ++ .../context/TestSubjectInspector.java | 13 +- .../classconfigdialog/CreateTestMeDialog.java | 197 ++++++++++++++++++ .../internal/velocity_implicit.vm | 2 + .../testMeIncludes/TestMe macros.java.ft | 6 +- .../Groovy, JUnit4 & Mockito.groovy.ft | 2 +- .../Groovy, Spock & Mockito.groovy.ft | 2 +- .../testMeTests/JUnit4 & Mockito.java.ft | 2 +- .../testMeTests/JUnit4 & Powermock.java.ft | 2 +- .../testMeTests/JUnit5 & Mockito.java.ft | 2 +- ...eterized Groovy, Spock & Mockito.groovy.ft | 2 +- .../testMeTests/Specs2 & Mockito.scala.ft | 2 +- .../testMeTests/TestNG & Mockito.java.ft | 2 +- 20 files changed, 330 insertions(+), 46 deletions(-) create mode 100644 src/main/java/com/weirddev/testme/intellij/ui/classconfigdialog/CreateTestMeDialog.java diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java index a68674d0..268e2e39 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java @@ -2,6 +2,7 @@ import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.ide.fileTemplates.FileTemplateDescriptor; +import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.psi.*; import com.weirddev.testme.intellij.BaseIJIntegrationTest; @@ -10,6 +11,7 @@ import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.FileTemplateContext; import com.weirddev.testme.intellij.template.context.Language; +import com.weirddev.testme.intellij.ui.template.TestMeTemplateManager; import org.jetbrains.annotations.NotNull; import org.junit.Assert; @@ -25,7 +27,6 @@ abstract public class TestMeGeneratorTestBase extends BaseIJIntegrationTest/*JavaCodeInsightFixtureTestCase */{ protected final String templateFilename; protected final String testDirectory; - private final TestTemplateContextBuilder testTemplateContextBuilder = mockTestTemplateContextBuilder(); private final Language language; protected String expectedTestClassExtension = "java"; protected boolean testEnabled = true; @@ -106,17 +107,18 @@ protected void doTest(final String packageName, String testSubjectClassName, fin final PsiDirectory srcDir = fooClass.getContainingFile().getContainingDirectory(); final PsiPackage targetPackage = JavaDirectoryService.getInstance().getPackage(srcDir); + FileTemplateContext fileTemplateContext = + new FileTemplateContext(new FileTemplateDescriptor(templateFilename), language, getProject(), + expectedTestClassName, targetPackage, getModule(), getModule(), srcDir, fooClass, fileTemplateConfig); + TestTemplateContextBuilder testTemplateContextBuilder = mockTestTemplateContextBuilder(); + FileTemplateManager + fileTemplateManager = TestMeTemplateManager.getInstance(fileTemplateContext.getTargetDirectory().getProject()); + final Map templateCtxtParams = testTemplateContextBuilder.build(fileTemplateContext, fileTemplateManager.getDefaultProperties()); + CommandProcessor.getInstance().executeCommand(getProject(), () -> { myFixture.openFileInEditor(fooClass.getContainingFile().getVirtualFile()); - PsiElement result = new TestMeGenerator(new TestClassElementsLocator(), testTemplateContextBuilder,new CodeRefactorUtil()).generateTest(new FileTemplateContext(new FileTemplateDescriptor(templateFilename), language, getProject(), - expectedTestClassName, - targetPackage, - getModule(), - getModule(), - srcDir, - fooClass, - fileTemplateConfig)); + PsiElement result = new TestMeGenerator(new TestClassElementsLocator(),new CodeRefactorUtil()).generateTest(fileTemplateContext, templateCtxtParams); System.out.println("result:"+result); verifyGeneratedTest(packageName, expectedTestClassName); }, CodeInsightBundle.message("intention.create.test"), this); diff --git a/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java b/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java index cce44d91..c24e6925 100644 --- a/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java +++ b/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java @@ -1,6 +1,7 @@ package com.weirddev.testme.intellij.action; import com.intellij.ide.fileTemplates.FileTemplateDescriptor; +import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; @@ -21,11 +22,16 @@ import com.weirddev.testme.intellij.action.helpers.ClassNameSelection; import com.weirddev.testme.intellij.action.helpers.GeneratedClassNameResolver; import com.weirddev.testme.intellij.action.helpers.TargetDirectoryLocator; +import com.weirddev.testme.intellij.builder.MethodReferencesBuilder; import com.weirddev.testme.intellij.configuration.TestMeConfigPersistent; +import com.weirddev.testme.intellij.generator.MockBuilderFactory; import com.weirddev.testme.intellij.generator.TestMeGenerator; +import com.weirddev.testme.intellij.generator.TestTemplateContextBuilder; import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.FileTemplateContext; import com.weirddev.testme.intellij.template.TemplateDescriptor; +import com.weirddev.testme.intellij.ui.classconfigdialog.CreateTestMeDialog; +import com.weirddev.testme.intellij.ui.template.TestMeTemplateManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; @@ -37,6 +43,7 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Map; /** * Date: 10/18/2016 @@ -107,23 +114,46 @@ public void invoke(@NotNull final Project project, Editor editor, @NotNull PsiEl } LOG.debug("targetDirectory:"+targetDirectory.getVirtualFile().getUrl()); final ClassNameSelection classNameSelection = generatedClassNameResolver.resolveClassName(project, targetDirectory, srcClass, templateDescriptor); - if (classNameSelection.getUserDecision() != ClassNameSelection.UserDecision.Abort) { - final Module finalTestModule = testModule; - CommandProcessor.getInstance().executeCommand(project, new Runnable() { - @Override - public void run() { - testMeGenerator.generateTest( - new FileTemplateContext( - new FileTemplateDescriptor(templateDescriptor.getFilename()),templateDescriptor.getLanguage(),project, classNameSelection.getClassName(), srcPackage, srcModule, finalTestModule,targetDirectory, srcClass, - new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState()) - ) - ); - } - }, "TestMe Generate Test", this); + if (classNameSelection.getUserDecision() == ClassNameSelection.UserDecision.Abort) { + return; } + final Module finalTestModule = testModule; + FileTemplateContext fileTemplateContext = new FileTemplateContext( + new FileTemplateDescriptor(templateDescriptor.getFilename()), templateDescriptor.getLanguage(), project, + classNameSelection.getClassName(), srcPackage, srcModule, finalTestModule, targetDirectory, srcClass, + new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState())); + + TestTemplateContextBuilder testTemplateContextBuilder = new TestTemplateContextBuilder(new MockBuilderFactory(), new MethodReferencesBuilder()); + FileTemplateManager fileTemplateManager = TestMeTemplateManager.getInstance(fileTemplateContext.getTargetDirectory().getProject()); + final Map templateCtxtParams = testTemplateContextBuilder.build(fileTemplateContext, fileTemplateManager.getDefaultProperties()); + + // create filed and method check dialog + final CreateTestMeDialog dialog = createTestMeDialog(project, fileTemplateContext.getSrcClass(), + fileTemplateContext.getFileTemplateDescriptor().getDisplayName(), templateCtxtParams); + // if not ok button selected the return + if (!dialog.showAndGet()) { + return; + } + + CommandProcessor.getInstance().executeCommand(project, new Runnable() { + @Override + public void run() { + testMeGenerator.generateTest(fileTemplateContext, templateCtxtParams); + } + }, "TestMe Generate Test", this); LOG.debug("End CreateTestMeAction.invoke"); } + /** + * create user check dialog to decide fields to mock and methods to test + */ + private CreateTestMeDialog createTestMeDialog(Project project, PsiClass srcClass, String templateFileName, + Map templateCtxtParams) { + return new CreateTestMeDialog(project, "Select Mock Fields And Test Methods", srcClass, templateFileName, + templateCtxtParams); + } + + /** * @see CreateTestAction#computeSuitableTestRootUrls */ diff --git a/src/main/java/com/weirddev/testme/intellij/generator/TestMeGenerator.java b/src/main/java/com/weirddev/testme/intellij/generator/TestMeGenerator.java index b6ebc0a3..706b71f7 100644 --- a/src/main/java/com/weirddev/testme/intellij/generator/TestMeGenerator.java +++ b/src/main/java/com/weirddev/testme/intellij/generator/TestMeGenerator.java @@ -21,7 +21,6 @@ import com.intellij.psi.search.GlobalSearchScopesCore; import com.intellij.testIntegration.createTest.JavaTestGenerator; import com.intellij.util.IncorrectOperationException; -import com.weirddev.testme.intellij.builder.MethodReferencesBuilder; import com.weirddev.testme.intellij.template.FileTemplateContext; import com.weirddev.testme.intellij.ui.template.TestMeTemplateManager; import org.apache.velocity.app.Velocity; @@ -38,21 +37,19 @@ */ public class TestMeGenerator { private final TestClassElementsLocator testClassElementsLocator; - private final TestTemplateContextBuilder testTemplateContextBuilder; private final CodeRefactorUtil codeRefactorUtil; private static final Logger LOG = Logger.getInstance(TestMeGenerator.class.getName()); public TestMeGenerator() { - this(new TestClassElementsLocator(), new TestTemplateContextBuilder(new MockBuilderFactory(), new MethodReferencesBuilder()),new CodeRefactorUtil()); + this(new TestClassElementsLocator(),new CodeRefactorUtil()); } - TestMeGenerator(TestClassElementsLocator testClassElementsLocator, TestTemplateContextBuilder testTemplateContextBuilder, CodeRefactorUtil codeRefactorUtil) { + TestMeGenerator(TestClassElementsLocator testClassElementsLocator, CodeRefactorUtil codeRefactorUtil) { this.testClassElementsLocator = testClassElementsLocator; - this.testTemplateContextBuilder = testTemplateContextBuilder; this.codeRefactorUtil = codeRefactorUtil; } - public PsiElement generateTest(final FileTemplateContext context) { + public PsiElement generateTest(final FileTemplateContext context, final Map templateCtxtParams) { final Project project = context.getProject(); return PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Computable() { public PsiElement compute() { @@ -61,7 +58,7 @@ public PsiElement compute() { try { final long start = new Date().getTime(); IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace(); - PsiFile targetClass = createTestClass(context); + PsiFile targetClass = createTestClass(context, templateCtxtParams); if (targetClass == null) { return null; } @@ -92,7 +89,7 @@ public PsiElement compute() { } @Nullable - private PsiFile createTestClass(FileTemplateContext context) { + private PsiFile createTestClass(FileTemplateContext context, Map templateCtxtParams) { final PsiDirectory targetDirectory = context.getTargetDirectory(); final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(targetDirectory); if (aPackage != null) { @@ -105,18 +102,17 @@ private PsiFile createTestClass(FileTemplateContext context) { return classes[0].getContainingFile(); } } - final PsiFile classFromTemplate = createTestClassFromCodeTemplate(context, targetDirectory); + final PsiFile classFromTemplate = createTestClassFromCodeTemplate(context, targetDirectory, templateCtxtParams); if (classFromTemplate != null) { return classFromTemplate; } return JavaDirectoryService.getInstance().createClass(targetDirectory, context.getTargetClass()).getContainingFile(); } - private PsiFile createTestClassFromCodeTemplate(final FileTemplateContext context, final PsiDirectory targetDirectory) { + private PsiFile createTestClassFromCodeTemplate(final FileTemplateContext context, final PsiDirectory targetDirectory, Map templateCtxtParams) { final String templateName = context.getFileTemplateDescriptor().getFileName(); - FileTemplateManager fileTemplateManager = TestMeTemplateManager.getInstance(targetDirectory.getProject()); - Map templateCtxtParams = testTemplateContextBuilder.build(context, fileTemplateManager.getDefaultProperties()); try { + FileTemplateManager fileTemplateManager = TestMeTemplateManager.getInstance(context.getTargetDirectory().getProject()); FileTemplate codeTemplate = fileTemplateManager.getInternalTemplate(templateName); codeTemplate.setReformatCode(false); Velocity.setProperty( Velocity.VM_MAX_DEPTH, 200); diff --git a/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java b/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java index 9e5e185d..1d9a26b7 100644 --- a/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java @@ -66,6 +66,8 @@ public Map build(FileTemplateContext context, Properties default ctxtParams.put(TestMeTemplateParams.MockitoMockBuilder, mockBuilderFactory.createMockitoMockBuilder(context, testSubjectInspector, classpathJars)); ctxtParams.put(TestMeTemplateParams.PowerMockBuilder, mockBuilderFactory.createPowerMockBuilder(context, testSubjectInspector, classpathJars)); ctxtParams.put(TestMeTemplateParams.TestedClasspathJars, classpathJars); + ctxtParams.put(TestMeTemplateParams.USER_CHECKED_MOCK_FIELDS, null); + ctxtParams.put(TestMeTemplateParams.USER_CHECKED_TEST_METHODS, null); logger.debug("Done building Test Template context in "+(new Date().getTime()-start)+" millis"); return ctxtParams; } diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockBuilder.java index 16596540..cf2d62d4 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockBuilder.java @@ -14,6 +14,11 @@ public interface MockBuilder { */ boolean isMockable(Field field, Type testedClass); + /** + * true - field should mock + */ + boolean isMockable(Field field, Type testedClass, List userCheckedFieldsList); + /** * constructs an error message explaining why field cannot be mocked * @param prefix add prefix to message diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index a76d771c..bf4ff0bc 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -118,6 +118,18 @@ public boolean isMockable(Field field) { */ @SuppressWarnings("unused") @Override + public boolean isMockable(Field field, Type testedClass, List userCheckedFieldsList) { + if (null != userCheckedFieldsList) { + return userCheckedFieldsList.contains(field.getName()); + } else { + return isMockable(field, testedClass); + } + } + + /** + * true - field can be mocked + */ + @Override public boolean isMockable(Field field, Type testedClass) { final boolean isMockable = !field.getType().isPrimitive() && !isWrapperType(field.getType()) && (!field.getType().isFinal() || isMockitoMockMakerInlineOn) && !field.isOverridden() diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java index 0e0a548c..fb4e8571 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java @@ -3,6 +3,8 @@ import com.intellij.openapi.diagnostic.Logger; import org.jetbrains.annotations.Nullable; +import java.util.List; + public class PowerMockBuilder extends MockitoMockBuilder{ private static final Logger LOG = Logger.getInstance(PowerMockBuilder.class.getName()); @@ -42,4 +44,16 @@ public boolean isMockable(Field field, Type testedClass) { return isMockable; } + /** + * true - field can be mocked + */ + @Override + public boolean isMockable(Field field, Type testedClass, List userCheckedFieldsList) { + if (null != userCheckedFieldsList) { + return userCheckedFieldsList.contains(field.getName()); + } else { + return isMockable(field, testedClass); + } + } + } diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java b/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java index 0d5b9558..680f4444 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java @@ -59,6 +59,19 @@ public interface TestMeTemplateParams { * @see TestSubjectInspector */ String TestedClasspathJars = "TestedClasspathJars"; + + /** + * user checked and selected mock field name list + * instance of {@link java.util.List} + */ + String USER_CHECKED_MOCK_FIELDS = "USER_CHECKED_MOCK_FIELDS"; + + /** + * user checked and selected test method id list + * instance of {@link java.util.List} + */ + String USER_CHECKED_TEST_METHODS = "USER_CHECKED_TEST_METHODS"; + /** * configured max recursion depth for object graph introspection * @see FileTemplateConfig#getMaxRecursionDepth() diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/TestSubjectInspector.java b/src/main/java/com/weirddev/testme/intellij/template/context/TestSubjectInspector.java index a23805e2..070ffdce 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/TestSubjectInspector.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/TestSubjectInspector.java @@ -34,7 +34,18 @@ public boolean hasTestableInstanceMethod(List methods) { } /** - * @return true - if method should is testable according to it's access modifiers and TestMe configuration + * @return true - method should test + */ + public boolean shouldBeTested(Method method, List userCheckedMethodIdList) { + if (null != userCheckedMethodIdList) { + return userCheckedMethodIdList.contains(method.getMethodId()); + } else { + return shouldBeTested(method); + } + } + + /** + * true - method should test */ public boolean shouldBeTested(Method method) { return method.isTestable() && ( generateTestsForInheritedMethods || !method.isInherited()); diff --git a/src/main/java/com/weirddev/testme/intellij/ui/classconfigdialog/CreateTestMeDialog.java b/src/main/java/com/weirddev/testme/intellij/ui/classconfigdialog/CreateTestMeDialog.java new file mode 100644 index 00000000..5910165c --- /dev/null +++ b/src/main/java/com/weirddev/testme/intellij/ui/classconfigdialog/CreateTestMeDialog.java @@ -0,0 +1,197 @@ +package com.weirddev.testme.intellij.ui.classconfigdialog; + +import java.util.*; +import java.util.List; + +import javax.swing.*; + +import com.intellij.psi.*; +import com.intellij.psi.util.InheritanceUtil; +import com.weirddev.testme.intellij.common.utils.PsiMethodUtils; +import com.weirddev.testme.intellij.template.TemplateRegistry; +import com.weirddev.testme.intellij.template.context.*; +import org.jetbrains.annotations.NotNull; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.DialogWrapper; +import com.intellij.openapi.util.NlsContexts; +import com.intellij.refactoring.ui.MemberSelectionTable; +import com.intellij.refactoring.util.classMembers.MemberInfo; +import com.intellij.ui.ScrollPaneFactory; + +/** + * + * dialog for user to check fields mockable and methods testable + * + * @author huangliang + */ +public class CreateTestMeDialog extends DialogWrapper { + + private final Map templateCtxtParams; + private final PsiClass myTargetClass; + private final String templateFileName; + private final MemberSelectionTable myMethodsTable = new MemberSelectionTable(Collections.emptyList(), null); + private final MemberSelectionTable myFieldsTable = new MemberSelectionTable(Collections.emptyList(), null); + private final List checkedFieldNameList = new ArrayList<>(); + private final List checkedMethodIdList = new ArrayList<>(); + + + public CreateTestMeDialog(@NotNull Project project, @NotNull @NlsContexts.DialogTitle String title, + PsiClass targetClass, String templateFileName, Map templateCtxtParams) { + super(project, true); + myTargetClass = targetClass; + this.templateCtxtParams = templateCtxtParams; + this.templateFileName = templateFileName; + setTitle(title); + init(); + } + + @Override + protected JComponent createCenterPanel() { + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); + + JLabel fieldLabel = new JLabel("Select Need Mocked Fields"); + panel.add(fieldLabel); + panel.add(ScrollPaneFactory.createScrollPane(myFieldsTable)); + + JLabel methodLabel = new JLabel("Select Need Test Methods"); + panel.add(methodLabel); + panel.add(ScrollPaneFactory.createScrollPane(myMethodsTable)); + + initExtractingClassMembers(); + return panel; + } + + /** + * update field is mockable or not after user checked + */ + private void updateClassMockableFields() { + Collection selectedMemberInfos = myFieldsTable.getSelectedMemberInfos(); + List userCheckedMockableFieldsList = + selectedMemberInfos.stream().map(e -> e.getMember().getName()).toList(); + Type classTypeObj = (Type)templateCtxtParams.get(TestMeTemplateParams.TESTED_CLASS); + for (Field field : classTypeObj.getFields()) { + if (userCheckedMockableFieldsList.contains(field.getName())) { + checkedFieldNameList.add(field.getName()); + } + } + templateCtxtParams.put(TestMeTemplateParams.USER_CHECKED_MOCK_FIELDS, checkedFieldNameList); + } + + /** + * update method is testable or not after user checked + */ + private void updateClassTestableMethods() { + Collection selectedMemberInfos = myMethodsTable.getSelectedMemberInfos(); + List testableMethodList = + selectedMemberInfos.stream().map(e -> PsiMethodUtils.formatMethodId((PsiMethod)e.getMember())).toList(); + Type classTypeObj = (Type)templateCtxtParams.get(TestMeTemplateParams.TESTED_CLASS); + for (Method method : classTypeObj.getMethods()) { + if (testableMethodList.contains(method.getMethodId())) { + checkedMethodIdList.add(method.getMethodId()); + } + } + templateCtxtParams.put(TestMeTemplateParams.USER_CHECKED_TEST_METHODS, checkedMethodIdList); + } + + /** + * init and extract class fields and methods for user to check + */ + public void initExtractingClassMembers() { + Set classes= InheritanceUtil.getSuperClasses(myTargetClass); + classes.add(myTargetClass); + + Type classTypeObj = (Type)templateCtxtParams.get(TestMeTemplateParams.TESTED_CLASS); + TestSubjectInspector testSubjectUtil = + (TestSubjectInspector)templateCtxtParams.get(TestMeTemplateParams.TestSubjectUtils); + MockBuilder templateMockBuilder = getTemplateMockBuilder(templateFileName); + + // build field mockable map, key = field name, value = true - if field mockable + Map fieldMockableMap = new HashMap<>(); + for (Field field : classTypeObj.getFields()) { + Boolean fieldMockable = templateMockBuilder.isMockable(field, classTypeObj); + fieldMockableMap.put(field.getName(), fieldMockable); + } + // build method testable map, key = method id, value = true - if method testable + Map methodTestableMap = new HashMap<>(); + for (Method method : classTypeObj.getMethods()) { + Boolean testable = testSubjectUtil.shouldBeTested(method); + methodTestableMap.put(method.getMethodId(), testable); + } + + // init method table and field table + List methodResult = new ArrayList<>(); + List fieldResult = new ArrayList<>(); + for (PsiClass aClass : classes) { + if (CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) + continue; + initMethodsTable(aClass, methodResult, methodTestableMap); + initFieldsTable(aClass, fieldResult, fieldMockableMap); + } + } + + /** + * get mock builder for template + * @param templateFileName template name + * @return MockBuilder + */ + private MockBuilder getTemplateMockBuilder(String templateFileName) { + if (TemplateRegistry.JUNIT4_POWERMOCK_JAVA_TEMPLATE.equals(templateFileName)) { + return (PowerMockBuilder)templateCtxtParams.get(TestMeTemplateParams.PowerMockBuilder); + } else { + return (MockitoMockBuilder)templateCtxtParams.get(TestMeTemplateParams.MockitoMockBuilder); + } + } + + private void initMethodsTable(PsiClass myTargetClass, List result, Map methodTestableMap) { + Set selectedMethods = new HashSet<>(); + MemberInfo.extractClassMembers(myTargetClass, result, member -> { + if (!(member instanceof PsiMethod method)) + return false; + String methodId = PsiMethodUtils.formatMethodId(method); + if (methodTestableMap.containsKey(methodId) && methodTestableMap.get(methodId)) { + selectedMethods.add(member); + return true; + } + return false; + }, false); + + for (MemberInfo each : result) { + each.setChecked(selectedMethods.contains(each.getMember())); + } + + myMethodsTable.setMemberInfos(result); + } + + private void initFieldsTable(PsiClass myTargetClass, List result, Map fieldMockableMap) { + Set selectedFields = new HashSet<>(); + MemberInfo.extractClassMembers(myTargetClass, result, member -> { + if (!(member instanceof PsiField field)) + return false; + if (fieldMockableMap.containsKey(field.getName()) && fieldMockableMap.get(field.getName())) { + selectedFields.add(member); + return true; + } + return false; + }, false); + + for (MemberInfo each : result) { + each.setChecked(selectedFields.contains(each.getMember())); + } + + myFieldsTable.setMemberInfos(result); + } + + @Override + protected String getDimensionServiceKey() { + return getClass().getName(); + } + + @Override + protected void doOKAction() { + updateClassMockableFields(); + updateClassTestableMethods(); + super.doOKAction(); + } + +} diff --git a/src/main/resources/fileTemplates/internal/velocity_implicit.vm b/src/main/resources/fileTemplates/internal/velocity_implicit.vm index 18692f27..79110fb9 100644 --- a/src/main/resources/fileTemplates/internal/velocity_implicit.vm +++ b/src/main/resources/fileTemplates/internal/velocity_implicit.vm @@ -12,4 +12,6 @@ #* @vtlvariable name="CLASS_NAME" type="java.lang.String" *# #* @vtlvariable name="MockitoMockBuilder" type="com.weirddev.testme.intellij.template.context.MockitoMockBuilder" *# #* @vtlvariable name="PowerMockBuilder" type="com.weirddev.testme.intellij.template.context.PowerMockBuilder" *# +#* @vtlvariable name="USER_CHECKED_MOCK_FIELDS" type="java.util.List" *# +#* @vtlvariable name="USER_CHECKED_TEST_METHODS" type="java.util.List" *# #* /fileTemplates/testMeIncludes/*.ft *# diff --git a/src/main/resources/fileTemplates/testMeIncludes/TestMe macros.java.ft b/src/main/resources/fileTemplates/testMeIncludes/TestMe macros.java.ft index 0d5c5ab1..f74050a2 100644 --- a/src/main/resources/fileTemplates/testMeIncludes/TestMe macros.java.ft +++ b/src/main/resources/fileTemplates/testMeIncludes/TestMe macros.java.ft @@ -57,7 +57,7 @@ ## #macro(renderMockedFields $hasMocks $testedClass) #foreach($field in $testedClass.fields) -#if($hasMocks && $mockBuilder.isMockable($field, $testedClass)) +#if($hasMocks && $mockBuilder.isMockable($field, $testedClass, $USER_CHECKED_MOCK_FIELDS)) @Mock $field.type.canonicalName $field.name; #elseif($mockBuilder.isMockExpected($field)) @@ -88,7 +88,7 @@ assertEquals(result#{if}($TestSubjectUtils.isJavaFuture($method.returnType)).get ## #macro(renderMockStubs $method $testedClass) #foreach($field in $testedClass.fields) -#if($mockBuilder.isMockable($field, $testedClass)) +#if($mockBuilder.isMockable($field, $testedClass, $USER_CHECKED_MOCK_FIELDS)) #foreach($fieldMethod in $field.type.methods) #if($fieldMethod.hasReturn() && $TestSubjectUtils.isMethodCalled($fieldMethod,$method)) when($field.name.${fieldMethod.name}($mockBuilder.buildMockArgsMatchers(${fieldMethod.methodParams},"Java"))).thenReturn($TestBuilder.renderReturnParam($method,$fieldMethod.returnType,"${fieldMethod.name}Response",$replacementTypes,$defaultTypeValues)); @@ -100,7 +100,7 @@ assertEquals(result#{if}($TestSubjectUtils.isJavaFuture($method.returnType)).get ## #macro(renderMockVerifies $method $testedClass) #foreach($field in $testedClass.fields) -#if($mockBuilder.isMockable($field, $testedClass)) +#if($mockBuilder.isMockable($field, $testedClass, $USER_CHECKED_MOCK_FIELDS)) #foreach($fieldMethod in $field.type.methods) #if(!$fieldMethod.hasReturn() && $TestSubjectUtils.isMethodCalled($fieldMethod,$method)) verify($field.name).${fieldMethod.name}($mockBuilder.buildMockArgsMatchers(${fieldMethod.methodParams},"Java")); diff --git a/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft index 99ea0025..b9e238f4 100644 --- a/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft @@ -25,7 +25,7 @@ class ${CLASS_NAME} { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method)) +#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) @Test void #renderTestMethodName($method.name)() { diff --git a/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft index 314590b1..51dfb147 100644 --- a/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft @@ -22,7 +22,7 @@ class ${CLASS_NAME} extends Specification { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method)) +#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) def "test #renderTestMethodNameAsWords($method.name)"() { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft index d9c6d64a..af910b79 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft @@ -26,7 +26,7 @@ public class ${CLASS_NAME} { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method)) +#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) @Test public void #renderTestMethodName($method.name)() throws Exception { diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft index 95cff5c4..14c23302 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft @@ -38,7 +38,7 @@ public class ${CLASS_NAME} { #end #foreach($method in $TESTED_CLASS.methods) - #if($TestSubjectUtils.shouldBeTested($method)) + #if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) @Test public void #renderTestMethodName($method.name)() throws Exception { #if($hasMocks && $PowerMockBuilder.shouldStub($method, $TESTED_CLASS)) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft index 7744a90e..ea9ce01f 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft @@ -25,7 +25,7 @@ class ${CLASS_NAME} { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method)) +#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) @Test void #renderTestMethodName($method.name)(){ diff --git a/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft index 2f0541fd..ddfaef49 100644 --- a/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft @@ -22,7 +22,7 @@ class ${CLASS_NAME} extends Specification { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method)) +#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) #set($paraTestComponents=$TestBuilder.buildPrameterizedTestComponents($method,$grReplacementTypesForReturn,$grReplacementTypes,$grDefaultTypeValues)) @Unroll diff --git a/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft b/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft index f0c72761..ac6b3a8a 100644 --- a/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft +++ b/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft @@ -27,7 +27,7 @@ class ${CLASS_NAME} extends Specification #if($hasMocks) with Mockito#end{ "$StringUtils.removeSuffix($TESTED_CLASS.name,"$")" should { #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method)) +#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) "#renderTestMethodNameAsWords($method.name)" in { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$constructor,$scDefaultTypeValues)) diff --git a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft index 7bd6df0d..466d5a15 100644 --- a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft @@ -25,7 +25,7 @@ public class ${CLASS_NAME} { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method)) +#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) @Test public void #renderTestMethodName($method.name)(){ From 87befe8c4f05f901f80ae7bc98713927e6d37424 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Mon, 25 Mar 2024 14:51:54 +0800 Subject: [PATCH 07/38] add user check dialog --- .../com/weirddev/testme/intellij/action/CreateTestMeAction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java b/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java index c24e6925..5cb104a2 100644 --- a/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java +++ b/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java @@ -131,7 +131,7 @@ public void invoke(@NotNull final Project project, Editor editor, @NotNull PsiEl final CreateTestMeDialog dialog = createTestMeDialog(project, fileTemplateContext.getSrcClass(), fileTemplateContext.getFileTemplateDescriptor().getDisplayName(), templateCtxtParams); // if not ok button selected the return - if (!dialog.showAndGet()) { + if (dialog.isModal() && !dialog.showAndGet()) { return; } From e17994dbf3347407266f79bbae2904748d7d709f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Mon, 25 Mar 2024 16:06:54 +0800 Subject: [PATCH 08/38] Throw specific exceptions based on the method under test --- .../fileTemplates/testMeTests/JUnit4 & Mockito.java.ft | 2 +- .../fileTemplates/testMeTests/JUnit4 & Powermock.java.ft | 2 +- .../fileTemplates/testMeTests/JUnit5 & Mockito.java.ft | 2 +- .../fileTemplates/testMeTests/TestNG & Mockito.java.ft | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft index 5e30eb5b..9ff9a3ea 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft @@ -29,7 +29,7 @@ public class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)() #if($method.hasException()) throws $method.methodExceptionTypes #end{ + public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end{ #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft index 14513f0f..518c1026 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft @@ -40,7 +40,7 @@ public class ${CLASS_NAME} { #foreach($method in $TESTED_CLASS.methods) #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)() #if($method.hasException()) throws $method.methodExceptionTypes #end { + public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end { #if($hasMocks && $PowerMockBuilder.shouldStub($method, $TESTED_CLASS)) #renderMockStubs($method, $TESTED_CLASS) #end diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft index 04d84852..18eb100a 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft @@ -28,7 +28,7 @@ class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - void #renderTestMethodName($method.name)() #if($method.hasException()) throws $method.methodExceptionTypes #end{ + void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end{ #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) diff --git a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft index da96443d..65f1645c 100644 --- a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft @@ -28,7 +28,7 @@ public class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)() #if($method.hasException()) throws $method.methodExceptionTypes #end{ + public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end{ #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) From 8cba2c583be571e9391dd65f353d06803c3aae5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Mon, 25 Mar 2024 16:12:23 +0800 Subject: [PATCH 09/38] Throw specific exceptions based on the method under test --- .../fileTemplates/testMeTests/JUnit4 & Powermock.java.ft | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft index 518c1026..871488ac 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft @@ -40,7 +40,7 @@ public class ${CLASS_NAME} { #foreach($method in $TESTED_CLASS.methods) #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end { + public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end{ #if($hasMocks && $PowerMockBuilder.shouldStub($method, $TESTED_CLASS)) #renderMockStubs($method, $TESTED_CLASS) #end From 488e926ba72536ba002ba739e895bd4a2a7d3433 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Mon, 25 Mar 2024 16:17:44 +0800 Subject: [PATCH 10/38] add user check dialog --- .../intellij/template/context/MockitoMockBuilder.java | 8 ++++---- .../testMeTests/Groovy, JUnit4 & Mockito.groovy.ft | 2 +- .../testMeTests/Groovy, Spock & Mockito.groovy.ft | 2 +- .../fileTemplates/testMeTests/JUnit4 & Mockito.java.ft | 2 +- .../fileTemplates/testMeTests/JUnit4 & Powermock.java.ft | 2 +- .../fileTemplates/testMeTests/JUnit5 & Mockito.java.ft | 2 +- .../Parameterized Groovy, Spock & Mockito.groovy.ft | 2 +- .../fileTemplates/testMeTests/TestNG & Mockito.java.ft | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index bf4ff0bc..154a6d0f 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -154,9 +154,9 @@ public boolean isMockable(Param param, Map defaultTypes) { * true - if any given field can be mocked */ @SuppressWarnings("unused") - public boolean hasMockable(List fields, Type testedClass) { + public boolean hasMockable(List fields, Type testedClass, List userCheckedFieldsList) { for (Field field : fields) { - if (isMockable(field, testedClass)) { + if (isMockable(field, testedClass, userCheckedFieldsList)) { return true; } } @@ -168,8 +168,8 @@ public boolean hasMockable(List fields, Type testedClass) { * @param testedClass the tested class * @return true - if the tested class has mockable field */ - public boolean hasMocks(Type testedClass) { - return testSubjectInspector.hasAccessibleCtor(testedClass) && hasMockable(testedClass.getFields(), testedClass); + public boolean hasMocks(Type testedClass, List userCheckedFieldsList) { + return testSubjectInspector.hasAccessibleCtor(testedClass) && hasMockable(testedClass.getFields(), testedClass, userCheckedFieldsList); } /** diff --git a/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft index b9e238f4..ec2f86e8 100644 --- a/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.groovy") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME} #end diff --git a/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft index 51dfb147..3c37bbe8 100644 --- a/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.groovy") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME} #end diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft index af910b79..34d6fd31 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.java") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME}; #end diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft index 14c23302..2228e4be 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.java") -#set($hasMocks=$PowerMockBuilder.hasMocks($TESTED_CLASS)) +#set($hasMocks=$PowerMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) #set($mockBuilder = $PowerMockBuilder) #if($PACKAGE_NAME) package ${PACKAGE_NAME}; diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft index ea9ce01f..838b15c7 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.java") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME}; #end diff --git a/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft index ddfaef49..25156e50 100644 --- a/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.groovy") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME} #end diff --git a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft index 466d5a15..50537077 100644 --- a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.java") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME}; #end From 3cb7ef0bad72d324ba912a33fa776fabe6af6cf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Mon, 25 Mar 2024 16:22:33 +0800 Subject: [PATCH 11/38] Throw specific exceptions based on the method under test --- .../fileTemplates/testMeTests/JUnit4 & Mockito.java.ft | 2 +- .../fileTemplates/testMeTests/JUnit4 & Powermock.java.ft | 2 +- .../fileTemplates/testMeTests/JUnit5 & Mockito.java.ft | 2 +- .../fileTemplates/testMeTests/TestNG & Mockito.java.ft | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft index 9ff9a3ea..b622356d 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft @@ -29,7 +29,7 @@ public class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end{ + public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes#end { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft index 871488ac..40f1f66e 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft @@ -40,7 +40,7 @@ public class ${CLASS_NAME} { #foreach($method in $TESTED_CLASS.methods) #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end{ + public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes#end { #if($hasMocks && $PowerMockBuilder.shouldStub($method, $TESTED_CLASS)) #renderMockStubs($method, $TESTED_CLASS) #end diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft index 18eb100a..57cc16cd 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft @@ -28,7 +28,7 @@ class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end{ + void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes#end { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) diff --git a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft index 65f1645c..9eaf45e4 100644 --- a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft @@ -28,7 +28,7 @@ public class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes #end{ + public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes#end { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) From 2cb44c975a11ceb27d695b6e6daad84b462c8d53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Mon, 25 Mar 2024 17:07:37 +0800 Subject: [PATCH 12/38] add a setting to open check dialog --- .../intellij/action/CreateTestMeAction.java | 20 ++++++------- .../intellij/configuration/TestMeConfig.java | 15 ++++++++++ .../intellij/template/FileTemplateConfig.java | 30 ++++++++++++++++--- .../ui/settings/TestMeSettingsForm.form | 11 ++++--- .../ui/settings/TestMeSettingsForm.java | 6 +++- 5 files changed, 63 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java b/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java index 5cb104a2..9dd4fab3 100644 --- a/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java +++ b/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java @@ -40,10 +40,7 @@ import org.jetbrains.jps.model.java.JavaSourceRootType; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; +import java.util.*; /** * Date: 10/18/2016 @@ -127,12 +124,15 @@ public void invoke(@NotNull final Project project, Editor editor, @NotNull PsiEl FileTemplateManager fileTemplateManager = TestMeTemplateManager.getInstance(fileTemplateContext.getTargetDirectory().getProject()); final Map templateCtxtParams = testTemplateContextBuilder.build(fileTemplateContext, fileTemplateManager.getDefaultProperties()); - // create filed and method check dialog - final CreateTestMeDialog dialog = createTestMeDialog(project, fileTemplateContext.getSrcClass(), - fileTemplateContext.getFileTemplateDescriptor().getDisplayName(), templateCtxtParams); - // if not ok button selected the return - if (dialog.isModal() && !dialog.showAndGet()) { - return; + boolean openUserCheckDialog = Objects.requireNonNull(TestMeConfigPersistent.getInstance().getState()).isOpenUserCheckDialog(); + if (openUserCheckDialog) { + // create filed and method check dialog + final CreateTestMeDialog dialog = createTestMeDialog(project, fileTemplateContext.getSrcClass(), + fileTemplateContext.getFileTemplateDescriptor().getDisplayName(), templateCtxtParams); + // if not ok button selected the return + if (dialog.isModal() && !dialog.showAndGet()) { + return; + } } CommandProcessor.getInstance().executeCommand(project, new Runnable() { diff --git a/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java b/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java index 0d663459..b99ff82e 100644 --- a/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java +++ b/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java @@ -38,6 +38,13 @@ public class TestMeConfig { */ private boolean renderInternalMethodCallStubs = false; + /** + * Test generator behavior option. open user check dialog + * Valid values:true,false + * Default:false + */ + private boolean openUserCheckDialog = false; + public boolean getGenerateTestsForInheritedMethods() { return generateTestsForInheritedMethods; } @@ -77,4 +84,12 @@ public boolean isRenderInternalMethodCallStubs() { public void setRenderInternalMethodCallStubs(boolean renderInternalMethodCallStubs) { this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; } + + public boolean isOpenUserCheckDialog() { + return openUserCheckDialog; + } + + public void setOpenUserCheckDialog(boolean openUserCheckDialog) { + this.openUserCheckDialog = openUserCheckDialog; + } } diff --git a/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java b/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java index 69ac6352..7c6fdb69 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java +++ b/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java @@ -86,10 +86,17 @@ public class FileTemplateConfig { /** * Test generator behavior option. Generate stubs for internal method calls in powermock * Valid values:true,false - * Default:true + * Default:false */ private boolean renderInternalMethodCallStubs = false; + /** + * Test generator behavior option. open user check dialog + * Valid values:true,false + * Default:false + */ + private boolean openUserCheckDialog = false; + public FileTemplateConfig(TestMeConfig testMeConfig) { this( Integer.valueOf(System.getProperties().getProperty("testMe.generator.maxRecursionDepth", FileTemplateConfig.DEFAULT_MAX_RECURSION_DEPTH + "")), @@ -98,6 +105,7 @@ public FileTemplateConfig(TestMeConfig testMeConfig) { testMeConfig == null || testMeConfig.getOptimizeImports(), testMeConfig == null || testMeConfig.getGenerateTestsForInheritedMethods(), testMeConfig == null || testMeConfig.isRenderInternalMethodCallStubs(), + testMeConfig == null || testMeConfig.isOpenUserCheckDialog(), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.ignoreUnusedProperties", "true")), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.replaceInterfaceParamsWithConcreteTypes", "true")), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.stubMockMethodCallsReturnValues", "true")), @@ -108,20 +116,26 @@ public FileTemplateConfig(TestMeConfig testMeConfig) { } - private FileTemplateConfig(int maxRecursionDepth, boolean reformatCode, boolean replaceFqn, boolean optimizeImports, boolean generateTestsForInheritedMethods, boolean renderInternalMethodCallStubs, boolean ignoreUnusedProperties, boolean replaceInterfaceParamsWithConcreteTypes, boolean stubMockMethodCallsReturnValues, - int maxNumOfConcreteCandidatesToReplaceInterfaceParam, int minPercentOfExcessiveSettersToPreferMapCtor, int minPercentOfInteractionWithPropertiesToTriggerConstructorOptimization) { + private FileTemplateConfig(int maxRecursionDepth, boolean reformatCode, boolean replaceFqn, boolean optimizeImports, + boolean generateTestsForInheritedMethods, boolean renderInternalMethodCallStubs, boolean openUserCheckDialog, + boolean ignoreUnusedProperties, boolean replaceInterfaceParamsWithConcreteTypes, + boolean stubMockMethodCallsReturnValues, int maxNumOfConcreteCandidatesToReplaceInterfaceParam, + int minPercentOfExcessiveSettersToPreferMapCtor, + int minPercentOfInteractionWithPropertiesToTriggerConstructorOptimization) { this.maxRecursionDepth = maxRecursionDepth; this.reformatCode = reformatCode; this.replaceFqn = replaceFqn; this.optimizeImports = optimizeImports; this.generateTestsForInheritedMethods = generateTestsForInheritedMethods; this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; + this.openUserCheckDialog = openUserCheckDialog; this.stubMockMethodCallsReturnValues = stubMockMethodCallsReturnValues; this.ignoreUnusedProperties = ignoreUnusedProperties; this.replaceInterfaceParamsWithConcreteTypes = replaceInterfaceParamsWithConcreteTypes; this.maxNumOfConcreteCandidatesToReplaceInterfaceParam = maxNumOfConcreteCandidatesToReplaceInterfaceParam; this.minPercentOfExcessiveSettersToPreferMapCtor = minPercentOfExcessiveSettersToPreferMapCtor; - this.minPercentOfInteractionWithPropertiesToTriggerConstructorOptimization = minPercentOfInteractionWithPropertiesToTriggerConstructorOptimization; + this.minPercentOfInteractionWithPropertiesToTriggerConstructorOptimization = + minPercentOfInteractionWithPropertiesToTriggerConstructorOptimization; } public boolean isReformatCode() { @@ -203,4 +217,12 @@ public boolean isRenderInternalMethodCallStubs() { public void setRenderInternalMethodCallStubs(boolean renderInternalMethodCallStubs) { this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; } + + public boolean isOpenUserCheckDialog() { + return openUserCheckDialog; + } + + public void setOpenUserCheckDialog(boolean openUserCheckDialog) { + this.openUserCheckDialog = openUserCheckDialog; + } } diff --git a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form index 31404120..d068c31c 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form +++ b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form @@ -13,7 +13,7 @@ - + @@ -42,11 +42,14 @@ - + - + - + + + + diff --git a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java index c9a037c0..c22ff7e2 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java @@ -18,6 +18,7 @@ public class TestMeSettingsForm implements Disposable { private JCheckBox replaceFullyQualifiedNamesCheckBox; private JPanel rootPanel; private JCheckBox renderInternalMethodCallStubsBox; + private JCheckBox openUserCheckDialogBox; public JPanel getRootPanel() { return rootPanel; @@ -35,6 +36,7 @@ public void persistState(TestMeConfig testMeConfig) { testMeConfig.setReformatCode(reformatCodeCheckBox.isSelected()); testMeConfig.setReplaceFullyQualifiedNames(replaceFullyQualifiedNamesCheckBox.isSelected()); testMeConfig.setRenderInternalMethodCallStubs(renderInternalMethodCallStubsBox.isSelected()); + testMeConfig.setOpenUserCheckDialog(openUserCheckDialogBox.isSelected()); } } @@ -45,6 +47,7 @@ public void reset(TestMeConfig state) { reformatCodeCheckBox.setSelected(state.getReformatCode()); replaceFullyQualifiedNamesCheckBox.setSelected(state.getReplaceFullyQualifiedNames()); renderInternalMethodCallStubsBox.setSelected(state.isRenderInternalMethodCallStubs()); + openUserCheckDialogBox.setSelected(state.isOpenUserCheckDialog()); } } @@ -54,7 +57,8 @@ public boolean isDirty(TestMeConfig state) { optimizeImportsCheckBox.isSelected() != state.getOptimizeImports() || reformatCodeCheckBox.isSelected() != state.getReformatCode() || replaceFullyQualifiedNamesCheckBox.isSelected() != state.getReplaceFullyQualifiedNames() || - renderInternalMethodCallStubsBox.isSelected() != state.isRenderInternalMethodCallStubs() + renderInternalMethodCallStubsBox.isSelected() != state.isRenderInternalMethodCallStubs() || + openUserCheckDialogBox.isSelected() != state.isOpenUserCheckDialog() ); } } From bf4b602f0f5501fc1f90e0d8c805a9d084c0892f Mon Sep 17 00:00:00 2001 From: Yaron Yamin Date: Mon, 25 Mar 2024 23:55:16 +0200 Subject: [PATCH 13/38] test generator: avoid mocking field that is initialized inline - apply on PowerMockBuilder as well. update IUT --- .../template/context/MockitoMockBuilder.java | 33 +++++++------------ .../template/context/PowerMockBuilder.java | 4 +-- .../src/com/example/services/impl/Foo.java | 2 +- .../com/example/services/impl/FooTest.java | 4 --- .../com/example/services/impl/FooTest.groovy | 4 --- .../com/example/services/impl/FooTest.java | 4 --- .../com/example/services/impl/FooTest.groovy | 3 -- .../com/example/services/impl/FooTest.java | 4 --- 8 files changed, 14 insertions(+), 44 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index c0b28292..5568c533 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -120,36 +120,27 @@ public boolean isMockable(Field field) { @SuppressWarnings("unused") @Override public boolean isMockable(Field field, Type testedClass) { - //todo extract common logic and reflect in powermock as well - final boolean isMockable = !field.getType().isPrimitive() && !isWrapperType(field.getType()) - && (!field.getType().isFinal() || isMockitoMockMakerInlineOn) && !field.isOverridden() - && !field.getType().isArray() && !field.getType().isEnum() - && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass) && !isInitInline(field); + final boolean isMockable = isMockableCommonChecks(field, testedClass) && (!field.getType().isFinal() || isMockitoMockMakerInlineOn); LOG.debug("field " + field.getType().getCanonicalName() + " " + field.getName() + " is mockable:" + isMockable); return isMockable; } + /** + * checks if field in testedClass can be mocked. evaluates conditions common to all currently supported mock frameworks + * @return true if input field in testedClass can be mocked + */ + protected boolean isMockableCommonChecks(Field field, Type testedClass) { + return !field.getType().isPrimitive() && !isWrapperType(field.getType()) + && !field.isOverridden() && !field.getType().isArray() && !field.getType().isEnum() + && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass) && !isInitInline(field); + } + private static boolean isInitInline(Field field) { //for now, avoid applying on all such fields since it's hard to deduct if default value overridden in ctor. settling for typical logger initialization pattern - //todo try to deduct if init in static block + //todo try to also deduct if init in static block return field.isInitializedInline() && !field.isHasSetter() && LOGGER_PATTERN.matcher(field.getName()).matches(); } - /** - * Avoid mocking a field if all these conditions are met: - * class has DI annotation - * field has no direct DI annotation - * field does not have a setter - * there is no class constructor. - * @param field field - * @param testedClass testedClass - * @return true if field meet conditions above - */ - private boolean isNotInjectedInDiClass(Field field, Type testedClass) { - return testedClass != null && testedClass.isAnnotatedByDI() && !field.isAnnotatedByDI() && !field.isHasSetter() - && !testedClass.hasConstructor(); - } - /** * true - if argument can be mocked given the provided default types */ diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java index 0e0a548c..b369f01d 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java @@ -35,9 +35,7 @@ public boolean hasInternalMethodCall(Method method, Type testedClass) { */ @Override public boolean isMockable(Field field, Type testedClass) { - final boolean isMockable = !field.getType().isPrimitive() && !isWrapperType(field.getType()) - && !field.isOverridden() && !field.getType().isArray() && !field.getType().isEnum() - && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass); + final boolean isMockable = isMockableCommonChecks(field, testedClass); LOG.debug("field " + field.getType().getCanonicalName() + " " + field.getName() + " is mockable:" + isMockable); return isMockable; } diff --git a/testData/testMeGenerator/mockReturned/src/com/example/services/impl/Foo.java b/testData/testMeGenerator/mockReturned/src/com/example/services/impl/Foo.java index 362f9531..3134ac82 100644 --- a/testData/testMeGenerator/mockReturned/src/com/example/services/impl/Foo.java +++ b/testData/testMeGenerator/mockReturned/src/com/example/services/impl/Foo.java @@ -12,7 +12,7 @@ public class Foo{ private FooFighter fooFighter; private Supplier result; - private Logger logger; + private Logger logger = Logger.getLogger(Foo.class.getName());; public String fight(Fire withFire,String foeName) { logger.trace("this method does not return a value so it should not be stubbed"); diff --git a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java index 5cddbb56..88d1bd62 100644 --- a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java @@ -1,7 +1,6 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; -import com.example.dependencies.Logger; import com.example.foes.Fire; import com.example.warriers.FooFighter; import org.junit.Assert; @@ -23,8 +22,6 @@ public class FooTest { FooFighter fooFighter; @Mock Supplier result; - @Mock - Logger logger; @InjectMocks Foo foo; @@ -39,7 +36,6 @@ public void testFight() throws Exception { when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); - verify(logger).trace(anyString()); Assert.assertEquals("replaceMeWithExpectedResult", result); } } diff --git a/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy index 6fd7bf1c..5cc6dc77 100644 --- a/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy @@ -1,7 +1,6 @@ package com.example.services.impl import com.example.beans.ConvertedBean -import com.example.dependencies.Logger import com.example.foes.Fear import com.example.foes.Fire import com.example.foes.Ice @@ -21,8 +20,6 @@ class FooTest { FooFighter fooFighter @Mock Supplier result - @Mock - Logger logger @InjectMocks Foo foo @@ -37,7 +34,6 @@ class FooTest { when(result.get()).thenReturn(0) String result = foo.fight(new Fire(), "foeName") - verify(logger).trace(anyString()) assert result == "replaceMeWithExpectedResult" } } diff --git a/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java index 1f917260..8327de76 100644 --- a/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java @@ -1,7 +1,6 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; -import com.example.dependencies.Logger; import com.example.foes.Fire; import com.example.warriers.FooFighter; import org.junit.jupiter.api.Assertions; @@ -23,8 +22,6 @@ class FooTest { FooFighter fooFighter; @Mock Supplier result; - @Mock - Logger logger; @InjectMocks Foo foo; @@ -39,7 +36,6 @@ void testFight() { when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); - verify(logger).trace(anyString()); Assertions.assertEquals("replaceMeWithExpectedResult", result); } } diff --git a/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy index 976e0685..7ebb3014 100644 --- a/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy @@ -1,7 +1,6 @@ package com.example.services.impl import com.example.beans.ConvertedBean -import com.example.dependencies.Logger import com.example.foes.Fear import com.example.foes.Fire import com.example.foes.Ice @@ -20,8 +19,6 @@ class FooTest extends Specification { FooFighter fooFighter @Mock Supplier result - @Mock - Logger logger @InjectMocks Foo foo diff --git a/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java index 0e389647..61072b1f 100644 --- a/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java @@ -1,7 +1,6 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; -import com.example.dependencies.Logger; import com.example.foes.Fire; import com.example.warriers.FooFighter; import org.mockito.InjectMocks; @@ -23,8 +22,6 @@ public class FooTest { FooFighter fooFighter; @Mock Supplier result; - @Mock - Logger logger; @InjectMocks Foo foo; @@ -39,7 +36,6 @@ public void testFight() { when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); - verify(logger).trace(anyString()); Assert.assertEquals(result, "replaceMeWithExpectedResult"); } } From 1671e0b200966f173e79298cf1c2309f9ffb3619 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Tue, 26 Mar 2024 11:43:08 +0800 Subject: [PATCH 14/38] Add a UI setting as "declare specific test method thrown exception types" --- .../intellij/builder/MethodFactory.java | 14 ++++++------- .../intellij/configuration/TestMeConfig.java | 16 ++++++++++++++ .../intellij/template/FileTemplateConfig.java | 21 ++++++++++++++++++- .../intellij/template/context/Method.java | 3 +-- .../ui/settings/TestMeSettingsForm.form | 10 ++++++++- .../ui/settings/TestMeSettingsForm.java | 8 ++++++- 6 files changed, 60 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java b/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java index 01156ec9..d1559122 100644 --- a/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java +++ b/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java @@ -57,8 +57,8 @@ public static Method createMethod(PsiMethod psiMethod, PsiClass srcClass, int ma Optional methodSubstitutor = findMethodSubstitutor(psiMethod, srcClass, ownerClassPsiType); Type returnType = resolveReturnType(psiMethod, maxRecursionDepth, typeDictionary, methodSubstitutor); List methodParams = extractMethodParams(psiMethod, isPrimaryConstructor, maxRecursionDepth, typeDictionary, methodSubstitutor); - String methodExceptionTypes = extractMethodExceptionTypes(psiMethod); - return new Method(methodId, methodName, returnType, ownerClassCanonicalType, methodParams, methodExceptionTypes,isPrivate, isProtected, isDefault, isPublic, isAbstract, isNative, + String throwsExceptions = extractMethodExceptionTypes(psiMethod); + return new Method(methodId, methodName, returnType, ownerClassCanonicalType, methodParams, throwsExceptions,isPrivate, isProtected, isDefault, isPublic, isAbstract, isNative, isStatic, isSetter, isGetter, isConstructor, overriddenInChild, inherited, isInterface, syntheticMethod, propertyName1, accessible, isPrimaryConstructor, testable); @@ -174,7 +174,7 @@ private static List extractMethodParams(PsiMethod psiMethod, boolean shou //analyze the exception types of the method private static String extractMethodExceptionTypes(PsiMethod psiMethod) { - String methodExceptionTypes = ""; + String throwsExceptions = ""; PsiReferenceList throwsList = psiMethod.getThrowsList(); PsiClassType[] referencedTypes = throwsList.getReferencedTypes(); @@ -182,13 +182,13 @@ private static String extractMethodExceptionTypes(PsiMethod psiMethod) { PsiClass resolved = type.resolve(); if (resolved != null) { String exceptionTypeName = getExceptionTypeName(resolved.getQualifiedName()); - methodExceptionTypes += exceptionTypeName+","; + throwsExceptions += exceptionTypeName+","; } } - if(StringUtils.isNotEmpty(methodExceptionTypes)){ - methodExceptionTypes = methodExceptionTypes.substring(0, methodExceptionTypes.length() - 1); + if(StringUtils.isNotEmpty(throwsExceptions)){ + throwsExceptions = throwsExceptions.substring(0, throwsExceptions.length() - 1); } - return methodExceptionTypes; + return throwsExceptions; } private static String getExceptionTypeName(String exceptionTypeName) { diff --git a/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java b/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java index 0d663459..4ad85668 100644 --- a/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java +++ b/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java @@ -38,6 +38,14 @@ public class TestMeConfig { */ private boolean renderInternalMethodCallStubs = false; + + /** + * Test generator behavior option. Declare specific test method thrown exception types + * Valid values:true,false + * Default:false + */ + private boolean throwSpecificExceptionTypes = false; + public boolean getGenerateTestsForInheritedMethods() { return generateTestsForInheritedMethods; } @@ -77,4 +85,12 @@ public boolean isRenderInternalMethodCallStubs() { public void setRenderInternalMethodCallStubs(boolean renderInternalMethodCallStubs) { this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; } + + public boolean isThrowSpecificExceptionTypes() { + return throwSpecificExceptionTypes; + } + + public void setThrowSpecificExceptionTypes(boolean throwSpecificExceptionTypes) { + this.throwSpecificExceptionTypes = throwSpecificExceptionTypes; + } } diff --git a/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java b/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java index 69ac6352..69479f62 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java +++ b/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java @@ -90,6 +90,14 @@ public class FileTemplateConfig { */ private boolean renderInternalMethodCallStubs = false; + + /** + * Test generator behavior option. Declare specific test method thrown exception types + * Valid values:true,false + * Default:false + */ + private boolean throwSpecificExceptionTypes = false; + public FileTemplateConfig(TestMeConfig testMeConfig) { this( Integer.valueOf(System.getProperties().getProperty("testMe.generator.maxRecursionDepth", FileTemplateConfig.DEFAULT_MAX_RECURSION_DEPTH + "")), @@ -98,6 +106,7 @@ public FileTemplateConfig(TestMeConfig testMeConfig) { testMeConfig == null || testMeConfig.getOptimizeImports(), testMeConfig == null || testMeConfig.getGenerateTestsForInheritedMethods(), testMeConfig == null || testMeConfig.isRenderInternalMethodCallStubs(), + testMeConfig == null || testMeConfig.isThrowSpecificExceptionTypes(), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.ignoreUnusedProperties", "true")), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.replaceInterfaceParamsWithConcreteTypes", "true")), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.stubMockMethodCallsReturnValues", "true")), @@ -108,7 +117,7 @@ public FileTemplateConfig(TestMeConfig testMeConfig) { } - private FileTemplateConfig(int maxRecursionDepth, boolean reformatCode, boolean replaceFqn, boolean optimizeImports, boolean generateTestsForInheritedMethods, boolean renderInternalMethodCallStubs, boolean ignoreUnusedProperties, boolean replaceInterfaceParamsWithConcreteTypes, boolean stubMockMethodCallsReturnValues, + private FileTemplateConfig(int maxRecursionDepth, boolean reformatCode, boolean replaceFqn, boolean optimizeImports, boolean generateTestsForInheritedMethods, boolean renderInternalMethodCallStubs,boolean throwSpecificExceptionTypes, boolean ignoreUnusedProperties, boolean replaceInterfaceParamsWithConcreteTypes, boolean stubMockMethodCallsReturnValues, int maxNumOfConcreteCandidatesToReplaceInterfaceParam, int minPercentOfExcessiveSettersToPreferMapCtor, int minPercentOfInteractionWithPropertiesToTriggerConstructorOptimization) { this.maxRecursionDepth = maxRecursionDepth; this.reformatCode = reformatCode; @@ -116,6 +125,7 @@ private FileTemplateConfig(int maxRecursionDepth, boolean reformatCode, boolean this.optimizeImports = optimizeImports; this.generateTestsForInheritedMethods = generateTestsForInheritedMethods; this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; + this.throwSpecificExceptionTypes = throwSpecificExceptionTypes; this.stubMockMethodCallsReturnValues = stubMockMethodCallsReturnValues; this.ignoreUnusedProperties = ignoreUnusedProperties; this.replaceInterfaceParamsWithConcreteTypes = replaceInterfaceParamsWithConcreteTypes; @@ -203,4 +213,13 @@ public boolean isRenderInternalMethodCallStubs() { public void setRenderInternalMethodCallStubs(boolean renderInternalMethodCallStubs) { this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; } + + public boolean isThrowSpecificExceptionTypes() { + return throwSpecificExceptionTypes; + } + + public void setThrowSpecificExceptionTypes(boolean throwSpecificExceptionTypes) { + this.throwSpecificExceptionTypes = throwSpecificExceptionTypes; + } + } diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/Method.java b/src/main/java/com/weirddev/testme/intellij/template/context/Method.java index a47f85b4..31f06fd5 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/Method.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/Method.java @@ -4,7 +4,6 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; -import org.apache.commons.lang.StringUtils; import java.util.HashSet; import java.util.List; @@ -163,7 +162,7 @@ public boolean hasParams() { * true - if method has Exception */ public boolean hasException(){ - return StringUtils.isNotEmpty(methodExceptionTypes); + return methodExceptionTypes != null && !methodExceptionTypes.trim().isEmpty(); } } diff --git a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form index 31404120..94a4eeb1 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form +++ b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form @@ -13,7 +13,7 @@ - + @@ -47,6 +47,14 @@ + + + + + + + + diff --git a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java index c9a037c0..e168ee5c 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java @@ -18,6 +18,7 @@ public class TestMeSettingsForm implements Disposable { private JCheckBox replaceFullyQualifiedNamesCheckBox; private JPanel rootPanel; private JCheckBox renderInternalMethodCallStubsBox; + private JCheckBox throwSpecificExceptionTypesCheckBox; public JPanel getRootPanel() { return rootPanel; @@ -35,6 +36,8 @@ public void persistState(TestMeConfig testMeConfig) { testMeConfig.setReformatCode(reformatCodeCheckBox.isSelected()); testMeConfig.setReplaceFullyQualifiedNames(replaceFullyQualifiedNamesCheckBox.isSelected()); testMeConfig.setRenderInternalMethodCallStubs(renderInternalMethodCallStubsBox.isSelected()); + testMeConfig.setThrowSpecificExceptionTypes(throwSpecificExceptionTypesCheckBox.isSelected()); + } } @@ -45,6 +48,8 @@ public void reset(TestMeConfig state) { reformatCodeCheckBox.setSelected(state.getReformatCode()); replaceFullyQualifiedNamesCheckBox.setSelected(state.getReplaceFullyQualifiedNames()); renderInternalMethodCallStubsBox.setSelected(state.isRenderInternalMethodCallStubs()); + throwSpecificExceptionTypesCheckBox.setSelected(state.isThrowSpecificExceptionTypes()); + } } @@ -54,7 +59,8 @@ public boolean isDirty(TestMeConfig state) { optimizeImportsCheckBox.isSelected() != state.getOptimizeImports() || reformatCodeCheckBox.isSelected() != state.getReformatCode() || replaceFullyQualifiedNamesCheckBox.isSelected() != state.getReplaceFullyQualifiedNames() || - renderInternalMethodCallStubsBox.isSelected() != state.isRenderInternalMethodCallStubs() + renderInternalMethodCallStubsBox.isSelected() != state.isRenderInternalMethodCallStubs()|| + throwSpecificExceptionTypesCheckBox.isSelected() != state.isThrowSpecificExceptionTypes() ); } } From 810722a60e565c7e8ddd4806053449eae67326f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Tue, 26 Mar 2024 14:55:12 +0800 Subject: [PATCH 15/38] update --- .../generator/TestMeGeneratorTestBase.java | 32 +++-- .../intellij/action/CreateTestMeAction.java | 39 +++--- .../intellij/builder/MethodFactory.java | 2 +- .../intellij/configuration/TestMeConfig.java | 10 +- .../generator/MockBuilderFactory.java | 10 +- .../intellij/generator/TestMeGenerator.java | 42 +++--- .../generator/TestTemplateContextBuilder.java | 6 +- .../intellij/template/FileTemplateConfig.java | 19 +-- .../template/FileTemplateContext.java | 11 +- .../intellij/template/context/Field.java | 2 +- .../template/context/MockBuilder.java | 5 - .../template/context/MockitoMockBuilder.java | 46 ++++--- .../template/context/PowerMockBuilder.java | 29 ++--- .../context/TestMeTemplateParams.java | 12 -- .../context/TestSubjectInspector.java | 24 ++-- .../CustomizeTestDialog.java} | 122 +++++++++--------- .../FileTemplateCustomization.java | 35 +++++ .../ui/settings/TestMeSettingsForm.form | 2 +- .../ui/settings/TestMeSettingsForm.java | 6 +- .../testMeIncludes/TestMe macros.java.ft | 6 +- .../Groovy, JUnit4 & Mockito.groovy.ft | 4 +- .../Groovy, Spock & Mockito.groovy.ft | 4 +- .../testMeTests/JUnit4 & Mockito.java.ft | 4 +- .../testMeTests/JUnit4 & Powermock.java.ft | 4 +- .../testMeTests/JUnit5 & Mockito.java.ft | 4 +- ...eterized Groovy, Spock & Mockito.groovy.ft | 4 +- .../testMeTests/Specs2 & Mockito.scala.ft | 4 +- .../testMeTests/TestNG & Mockito.java.ft | 4 +- 28 files changed, 241 insertions(+), 251 deletions(-) rename src/main/java/com/weirddev/testme/intellij/ui/{classconfigdialog/CreateTestMeDialog.java => customizedialog/CustomizeTestDialog.java} (53%) create mode 100644 src/main/java/com/weirddev/testme/intellij/ui/customizedialog/FileTemplateCustomization.java diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java index 268e2e39..ebf01894 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java @@ -2,7 +2,6 @@ import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.ide.fileTemplates.FileTemplateDescriptor; -import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.psi.*; import com.weirddev.testme.intellij.BaseIJIntegrationTest; @@ -11,13 +10,11 @@ import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.FileTemplateContext; import com.weirddev.testme.intellij.template.context.Language; -import com.weirddev.testme.intellij.ui.template.TestMeTemplateManager; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; import org.jetbrains.annotations.NotNull; import org.junit.Assert; -import java.util.GregorianCalendar; -import java.util.Map; -import java.util.Properties; +import java.util.*; /** * Date: 13/12/2016 @@ -27,6 +24,7 @@ abstract public class TestMeGeneratorTestBase extends BaseIJIntegrationTest/*JavaCodeInsightFixtureTestCase */{ protected final String templateFilename; protected final String testDirectory; + private final TestTemplateContextBuilder testTemplateContextBuilder = mockTestTemplateContextBuilder(); private final Language language; protected String expectedTestClassExtension = "java"; protected boolean testEnabled = true; @@ -107,18 +105,18 @@ protected void doTest(final String packageName, String testSubjectClassName, fin final PsiDirectory srcDir = fooClass.getContainingFile().getContainingDirectory(); final PsiPackage targetPackage = JavaDirectoryService.getInstance().getPackage(srcDir); - FileTemplateContext fileTemplateContext = - new FileTemplateContext(new FileTemplateDescriptor(templateFilename), language, getProject(), - expectedTestClassName, targetPackage, getModule(), getModule(), srcDir, fooClass, fileTemplateConfig); - TestTemplateContextBuilder testTemplateContextBuilder = mockTestTemplateContextBuilder(); - FileTemplateManager - fileTemplateManager = TestMeTemplateManager.getInstance(fileTemplateContext.getTargetDirectory().getProject()); - final Map templateCtxtParams = testTemplateContextBuilder.build(fileTemplateContext, fileTemplateManager.getDefaultProperties()); - CommandProcessor.getInstance().executeCommand(getProject(), () -> { myFixture.openFileInEditor(fooClass.getContainingFile().getVirtualFile()); - PsiElement result = new TestMeGenerator(new TestClassElementsLocator(),new CodeRefactorUtil()).generateTest(fileTemplateContext, templateCtxtParams); + PsiElement result = new TestMeGenerator(new TestClassElementsLocator(), testTemplateContextBuilder,new CodeRefactorUtil()).generateTest(new FileTemplateContext(new FileTemplateDescriptor(templateFilename), language, getProject(), + expectedTestClassName, + targetPackage, + getModule(), + getModule(), + srcDir, + fooClass, + fileTemplateConfig, + new FileTemplateCustomization(new ArrayList<>(), new ArrayList<>(), false))); System.out.println("result:"+result); verifyGeneratedTest(packageName, expectedTestClassName); }, CodeInsightBundle.message("intention.create.test"), this); @@ -159,7 +157,7 @@ public void setUp() throws Exception { ignoreTrailingWhitespaces = false; } // @Override //relevant when JavaCodeInsightFixtureTestCase is used -// protected void tuneFixture(JavaModuleFixtureBuilder moduleBuilder) throws Exception { -// moduleBuilder.addJdk(new File(System.getProperty("java.home")).getParentContainerClass()); -// } + // protected void tuneFixture(JavaModuleFixtureBuilder moduleBuilder) throws Exception { + // moduleBuilder.addJdk(new File(System.getProperty("java.home")).getParentContainerClass()); + // } } diff --git a/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java b/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java index 9dd4fab3..6e5dd527 100644 --- a/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java +++ b/src/main/java/com/weirddev/testme/intellij/action/CreateTestMeAction.java @@ -1,7 +1,6 @@ package com.weirddev.testme.intellij.action; import com.intellij.ide.fileTemplates.FileTemplateDescriptor; -import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; @@ -22,16 +21,13 @@ import com.weirddev.testme.intellij.action.helpers.ClassNameSelection; import com.weirddev.testme.intellij.action.helpers.GeneratedClassNameResolver; import com.weirddev.testme.intellij.action.helpers.TargetDirectoryLocator; -import com.weirddev.testme.intellij.builder.MethodReferencesBuilder; import com.weirddev.testme.intellij.configuration.TestMeConfigPersistent; -import com.weirddev.testme.intellij.generator.MockBuilderFactory; import com.weirddev.testme.intellij.generator.TestMeGenerator; -import com.weirddev.testme.intellij.generator.TestTemplateContextBuilder; import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.FileTemplateContext; import com.weirddev.testme.intellij.template.TemplateDescriptor; -import com.weirddev.testme.intellij.ui.classconfigdialog.CreateTestMeDialog; -import com.weirddev.testme.intellij.ui.template.TestMeTemplateManager; +import com.weirddev.testme.intellij.ui.customizedialog.CustomizeTestDialog; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes; @@ -40,7 +36,9 @@ import org.jetbrains.jps.model.java.JavaSourceRootType; import java.lang.reflect.Method; -import java.util.*; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; /** * Date: 10/18/2016 @@ -111,24 +109,20 @@ public void invoke(@NotNull final Project project, Editor editor, @NotNull PsiEl } LOG.debug("targetDirectory:"+targetDirectory.getVirtualFile().getUrl()); final ClassNameSelection classNameSelection = generatedClassNameResolver.resolveClassName(project, targetDirectory, srcClass, templateDescriptor); - if (classNameSelection.getUserDecision() == ClassNameSelection.UserDecision.Abort) { + if (classNameSelection.getUserDecision().equals(ClassNameSelection.UserDecision.Abort)) { return; } + + FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState()); final Module finalTestModule = testModule; + boolean openUserCheckDialog = TestMeConfigPersistent.getInstance().getState().isOpenCustomizeTestDialog(); FileTemplateContext fileTemplateContext = new FileTemplateContext( new FileTemplateDescriptor(templateDescriptor.getFilename()), templateDescriptor.getLanguage(), project, classNameSelection.getClassName(), srcPackage, srcModule, finalTestModule, targetDirectory, srcClass, - new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState())); - - TestTemplateContextBuilder testTemplateContextBuilder = new TestTemplateContextBuilder(new MockBuilderFactory(), new MethodReferencesBuilder()); - FileTemplateManager fileTemplateManager = TestMeTemplateManager.getInstance(fileTemplateContext.getTargetDirectory().getProject()); - final Map templateCtxtParams = testTemplateContextBuilder.build(fileTemplateContext, fileTemplateManager.getDefaultProperties()); - - boolean openUserCheckDialog = Objects.requireNonNull(TestMeConfigPersistent.getInstance().getState()).isOpenUserCheckDialog(); + fileTemplateConfig, new FileTemplateCustomization(new ArrayList<>(), new ArrayList<>(), openUserCheckDialog)); if (openUserCheckDialog) { // create filed and method check dialog - final CreateTestMeDialog dialog = createTestMeDialog(project, fileTemplateContext.getSrcClass(), - fileTemplateContext.getFileTemplateDescriptor().getDisplayName(), templateCtxtParams); + final CustomizeTestDialog dialog = createTestMeDialog(project, srcClass, fileTemplateContext); // if not ok button selected the return if (dialog.isModal() && !dialog.showAndGet()) { return; @@ -138,7 +132,7 @@ public void invoke(@NotNull final Project project, Editor editor, @NotNull PsiEl CommandProcessor.getInstance().executeCommand(project, new Runnable() { @Override public void run() { - testMeGenerator.generateTest(fileTemplateContext, templateCtxtParams); + testMeGenerator.generateTest(fileTemplateContext); } }, "TestMe Generate Test", this); LOG.debug("End CreateTestMeAction.invoke"); @@ -147,13 +141,10 @@ public void run() { /** * create user check dialog to decide fields to mock and methods to test */ - private CreateTestMeDialog createTestMeDialog(Project project, PsiClass srcClass, String templateFileName, - Map templateCtxtParams) { - return new CreateTestMeDialog(project, "Select Mock Fields And Test Methods", srcClass, templateFileName, - templateCtxtParams); + private CustomizeTestDialog createTestMeDialog(Project project, PsiClass srcClass, FileTemplateContext fileTemplateContext) { + return new CustomizeTestDialog(project, "Select fields/methods to be mocked/tested", srcClass, fileTemplateContext); } - /** * @see CreateTestAction#computeSuitableTestRootUrls */ @@ -180,7 +171,7 @@ private static List suitableTestSourceFolders(@NotNull Module modu return sourceFolders; } /** - * @see JavaProjectRootsUtil#isForGeneratedSources(com.intellij.openapi.roots.SourceFolder) + * @see JavaProjectRootsUtil#isForGeneratedSources(SourceFolder) */ private static boolean isForGeneratedSources(SourceFolder sourceFolder) { JavaSourceRootProperties properties = sourceFolder.getJpsElement().getProperties(JavaModuleSourceRootTypes.SOURCES); diff --git a/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java b/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java index c9d473a9..e0b19954 100644 --- a/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java +++ b/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java @@ -249,7 +249,7 @@ private static String resolveOwnerClassName(PsiMethod psiMethod) { return psiMethod.getContainingClass() == null ? null : psiMethod.getContainingClass().getQualifiedName(); } - private static boolean isTestable(PsiMethod psiMethod, @Nullable PsiClass srcClass){ + public static boolean isTestable(PsiMethod psiMethod, @Nullable PsiClass srcClass){ return !TypeUtils.isLanguageBaseClass(resolveOwnerClassName(psiMethod)) && !PropertyUtils.isPropertySetter(psiMethod) && (!PropertyUtils.isPropertyGetter(psiMethod) || srcClass!=null && srcClass.isEnum()) && !psiMethod.isConstructor() && isVisibleForTest(psiMethod, srcClass) && !isOverriddenInChild(psiMethod, srcClass) && !isInterface(psiMethod) && !psiMethod.hasModifierProperty(PsiModifier.ABSTRACT) && !isSyntheticMethod(psiMethod); diff --git a/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java b/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java index b99ff82e..103111bd 100644 --- a/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java +++ b/src/main/java/com/weirddev/testme/intellij/configuration/TestMeConfig.java @@ -43,7 +43,7 @@ public class TestMeConfig { * Valid values:true,false * Default:false */ - private boolean openUserCheckDialog = false; + private boolean openCustomizeTestDialog = false; public boolean getGenerateTestsForInheritedMethods() { return generateTestsForInheritedMethods; @@ -85,11 +85,11 @@ public void setRenderInternalMethodCallStubs(boolean renderInternalMethodCallStu this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; } - public boolean isOpenUserCheckDialog() { - return openUserCheckDialog; + public boolean isOpenCustomizeTestDialog() { + return openCustomizeTestDialog; } - public void setOpenUserCheckDialog(boolean openUserCheckDialog) { - this.openUserCheckDialog = openUserCheckDialog; + public void setOpenCustomizeTestDialog(boolean openCustomizeTestDialog) { + this.openCustomizeTestDialog = openCustomizeTestDialog; } } diff --git a/src/main/java/com/weirddev/testme/intellij/generator/MockBuilderFactory.java b/src/main/java/com/weirddev/testme/intellij/generator/MockBuilderFactory.java index 7b38b8c8..01423d95 100644 --- a/src/main/java/com/weirddev/testme/intellij/generator/MockBuilderFactory.java +++ b/src/main/java/com/weirddev/testme/intellij/generator/MockBuilderFactory.java @@ -31,18 +31,18 @@ public MockitoMockBuilder createMockitoMockBuilder(FileTemplateContext context, TestSubjectInspector testSubjectInspector, List classpathJars) { return new MockitoMockBuilder(isMockInline(context), context.getFileTemplateConfig().isStubMockMethodCallsReturnValues(), testSubjectInspector, - resolveMockitoVersion(classpathJars)); + resolveMockitoVersion(classpathJars), context.getFileTemplateCustomization()); } @NotNull public PowerMockBuilder createPowerMockBuilder(FileTemplateContext context, TestSubjectInspector testSubjectInspector, List classpathJars) { - return new PowerMockBuilder(true, - context.getFileTemplateConfig().isStubMockMethodCallsReturnValues(), testSubjectInspector, - resolveMockitoVersion(classpathJars), context.getFileTemplateConfig().isRenderInternalMethodCallStubs()); + return new PowerMockBuilder(true, context.getFileTemplateConfig().isStubMockMethodCallsReturnValues(), + testSubjectInspector, resolveMockitoVersion(classpathJars), + context.getFileTemplateConfig().isRenderInternalMethodCallStubs(), context.getFileTemplateCustomization()); } - private boolean isMockInline(FileTemplateContext context) { + public static boolean isMockInline(FileTemplateContext context) { boolean found = false; // final VirtualFile mockMakerVFile = ResourceFileUtil.findResourceFileInScope("mockito-extensions/org.mockito.plugins.MockMaker", context.getProject(), context.getTestModule().getModuleWithDependenciesAndLibrariesScope(true)); final VirtualFile mockMakerVFile = ResourceFileUtil.findResourceFileInDependents(context.getTestModule(), "mockito-extensions/org.mockito.plugins.MockMaker"); diff --git a/src/main/java/com/weirddev/testme/intellij/generator/TestMeGenerator.java b/src/main/java/com/weirddev/testme/intellij/generator/TestMeGenerator.java index 706b71f7..1dcd0e50 100644 --- a/src/main/java/com/weirddev/testme/intellij/generator/TestMeGenerator.java +++ b/src/main/java/com/weirddev/testme/intellij/generator/TestMeGenerator.java @@ -21,6 +21,7 @@ import com.intellij.psi.search.GlobalSearchScopesCore; import com.intellij.testIntegration.createTest.JavaTestGenerator; import com.intellij.util.IncorrectOperationException; +import com.weirddev.testme.intellij.builder.MethodReferencesBuilder; import com.weirddev.testme.intellij.template.FileTemplateContext; import com.weirddev.testme.intellij.ui.template.TestMeTemplateManager; import org.apache.velocity.app.Velocity; @@ -37,19 +38,21 @@ */ public class TestMeGenerator { private final TestClassElementsLocator testClassElementsLocator; + private final TestTemplateContextBuilder testTemplateContextBuilder; private final CodeRefactorUtil codeRefactorUtil; private static final Logger LOG = Logger.getInstance(TestMeGenerator.class.getName()); public TestMeGenerator() { - this(new TestClassElementsLocator(),new CodeRefactorUtil()); + this(new TestClassElementsLocator(), new TestTemplateContextBuilder(new MockBuilderFactory(), new MethodReferencesBuilder()),new CodeRefactorUtil()); } - - TestMeGenerator(TestClassElementsLocator testClassElementsLocator, CodeRefactorUtil codeRefactorUtil) { + + TestMeGenerator(TestClassElementsLocator testClassElementsLocator, TestTemplateContextBuilder testTemplateContextBuilder, CodeRefactorUtil codeRefactorUtil) { this.testClassElementsLocator = testClassElementsLocator; + this.testTemplateContextBuilder = testTemplateContextBuilder; this.codeRefactorUtil = codeRefactorUtil; } - public PsiElement generateTest(final FileTemplateContext context, final Map templateCtxtParams) { + public PsiElement generateTest(final FileTemplateContext context) { final Project project = context.getProject(); return PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Computable() { public PsiElement compute() { @@ -58,7 +61,7 @@ public PsiElement compute() { try { final long start = new Date().getTime(); IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace(); - PsiFile targetClass = createTestClass(context, templateCtxtParams); + PsiFile targetClass = createTestClass(context); if (targetClass == null) { return null; } @@ -74,7 +77,7 @@ public PsiElement compute() { } } catch (Throwable e) { LOG.warn("unable to locate optimal cursor location post test generation",e); -// new OpenFileDescriptor(project, targetClass.getContainingFile().getVirtualFile()).navigate(true); + // new OpenFileDescriptor(project, targetClass.getContainingFile().getVirtualFile()).navigate(true); } LOG.debug("Done generating class "+context.getTargetClass()+" in "+(new Date().getTime()-start)+" millis"); return targetClass; @@ -89,7 +92,7 @@ public PsiElement compute() { } @Nullable - private PsiFile createTestClass(FileTemplateContext context, Map templateCtxtParams) { + private PsiFile createTestClass(FileTemplateContext context) { final PsiDirectory targetDirectory = context.getTargetDirectory(); final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(targetDirectory); if (aPackage != null) { @@ -102,17 +105,18 @@ private PsiFile createTestClass(FileTemplateContext context, Map return classes[0].getContainingFile(); } } - final PsiFile classFromTemplate = createTestClassFromCodeTemplate(context, targetDirectory, templateCtxtParams); + final PsiFile classFromTemplate = createTestClassFromCodeTemplate(context, targetDirectory); if (classFromTemplate != null) { return classFromTemplate; } return JavaDirectoryService.getInstance().createClass(targetDirectory, context.getTargetClass()).getContainingFile(); } - private PsiFile createTestClassFromCodeTemplate(final FileTemplateContext context, final PsiDirectory targetDirectory, Map templateCtxtParams) { + private PsiFile createTestClassFromCodeTemplate(final FileTemplateContext context, final PsiDirectory targetDirectory) { final String templateName = context.getFileTemplateDescriptor().getFileName(); + FileTemplateManager fileTemplateManager = TestMeTemplateManager.getInstance(targetDirectory.getProject()); + Map templateCtxtParams = testTemplateContextBuilder.build(context, fileTemplateManager.getDefaultProperties()); try { - FileTemplateManager fileTemplateManager = TestMeTemplateManager.getInstance(context.getTargetDirectory().getProject()); FileTemplate codeTemplate = fileTemplateManager.getInternalTemplate(templateName); codeTemplate.setReformatCode(false); Velocity.setProperty( Velocity.VM_MAX_DEPTH, 200); @@ -137,19 +141,19 @@ private PsiFile createTestClassFromCodeTemplate(final FileTemplateContext contex CodeStyleManager.getInstance(context.getProject()).reformatText(containingFile, textRange.getStartOffset(), textRange.getEndOffset()); } LOG.debug("Done reformatting generated PsiClass in "+(new Date().getTime()-startReformating)+" millis"); - return psiFile; + return psiFile; } catch (Exception e) { LOG.error("error generating test class",e); return null; } } -// private void flushOperations(FileTemplateContext context, PsiClass psiClass) { -// final Document document = psiClass.getContainingFile().getViewProvider().getDocument(); -// if (document != null) { -// PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(document); -// } -// } + // private void flushOperations(FileTemplateContext context, PsiClass psiClass) { + // final Document document = psiClass.getContainingFile().getViewProvider().getDocument(); + // if (document != null) { + // PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(document); + // } + // } private PsiElement resolveEmbeddedClass(PsiElement psiElement) { //Important for Groovy support - expecting org.jetbrains.plugins.groovy.lang.psi.GroovyFile. see org.jetbrains.plugins.groovy.annotator.intentions.CreateClassActionBase.createClassByType @@ -184,8 +188,8 @@ static void showErrorLater(final Project project, final String targetClassName) ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { Messages.showErrorDialog(project, - CodeInsightBundle.message("intention.error.cannot.create.class.message", targetClassName), - CodeInsightBundle.message("intention.error.cannot.create.class.title")); + CodeInsightBundle.message("intention.error.cannot.create.class.message", targetClassName), + CodeInsightBundle.message("intention.error.cannot.create.class.title")); } }); } diff --git a/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java b/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java index 1d9a26b7..70dca3a9 100644 --- a/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java @@ -60,14 +60,14 @@ public Map build(FileTemplateContext context, Properties default methodReferencesBuilder.resolveMethodReferences(maxRecursionDepth, type.getMethods()); } } - final TestSubjectInspector testSubjectInspector = new TestSubjectInspector(context.getFileTemplateConfig().isGenerateTestsForInheritedMethods()); + final TestSubjectInspector testSubjectInspector = + new TestSubjectInspector(context.getFileTemplateConfig().isGenerateTestsForInheritedMethods(), + context.getFileTemplateCustomization()); ctxtParams.put(TestMeTemplateParams.TestSubjectUtils, testSubjectInspector); List classpathJars = resolveClasspathJars(context); ctxtParams.put(TestMeTemplateParams.MockitoMockBuilder, mockBuilderFactory.createMockitoMockBuilder(context, testSubjectInspector, classpathJars)); ctxtParams.put(TestMeTemplateParams.PowerMockBuilder, mockBuilderFactory.createPowerMockBuilder(context, testSubjectInspector, classpathJars)); ctxtParams.put(TestMeTemplateParams.TestedClasspathJars, classpathJars); - ctxtParams.put(TestMeTemplateParams.USER_CHECKED_MOCK_FIELDS, null); - ctxtParams.put(TestMeTemplateParams.USER_CHECKED_TEST_METHODS, null); logger.debug("Done building Test Template context in "+(new Date().getTime()-start)+" millis"); return ctxtParams; } diff --git a/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java b/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java index 7c6fdb69..46d27d2d 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java +++ b/src/main/java/com/weirddev/testme/intellij/template/FileTemplateConfig.java @@ -90,13 +90,6 @@ public class FileTemplateConfig { */ private boolean renderInternalMethodCallStubs = false; - /** - * Test generator behavior option. open user check dialog - * Valid values:true,false - * Default:false - */ - private boolean openUserCheckDialog = false; - public FileTemplateConfig(TestMeConfig testMeConfig) { this( Integer.valueOf(System.getProperties().getProperty("testMe.generator.maxRecursionDepth", FileTemplateConfig.DEFAULT_MAX_RECURSION_DEPTH + "")), @@ -105,7 +98,6 @@ public FileTemplateConfig(TestMeConfig testMeConfig) { testMeConfig == null || testMeConfig.getOptimizeImports(), testMeConfig == null || testMeConfig.getGenerateTestsForInheritedMethods(), testMeConfig == null || testMeConfig.isRenderInternalMethodCallStubs(), - testMeConfig == null || testMeConfig.isOpenUserCheckDialog(), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.ignoreUnusedProperties", "true")), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.replaceInterfaceParamsWithConcreteTypes", "true")), Boolean.valueOf(System.getProperties().getProperty("testMe.generator.stubMockMethodCallsReturnValues", "true")), @@ -117,7 +109,7 @@ public FileTemplateConfig(TestMeConfig testMeConfig) { } private FileTemplateConfig(int maxRecursionDepth, boolean reformatCode, boolean replaceFqn, boolean optimizeImports, - boolean generateTestsForInheritedMethods, boolean renderInternalMethodCallStubs, boolean openUserCheckDialog, + boolean generateTestsForInheritedMethods, boolean renderInternalMethodCallStubs, boolean ignoreUnusedProperties, boolean replaceInterfaceParamsWithConcreteTypes, boolean stubMockMethodCallsReturnValues, int maxNumOfConcreteCandidatesToReplaceInterfaceParam, int minPercentOfExcessiveSettersToPreferMapCtor, @@ -128,7 +120,6 @@ private FileTemplateConfig(int maxRecursionDepth, boolean reformatCode, boolean this.optimizeImports = optimizeImports; this.generateTestsForInheritedMethods = generateTestsForInheritedMethods; this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; - this.openUserCheckDialog = openUserCheckDialog; this.stubMockMethodCallsReturnValues = stubMockMethodCallsReturnValues; this.ignoreUnusedProperties = ignoreUnusedProperties; this.replaceInterfaceParamsWithConcreteTypes = replaceInterfaceParamsWithConcreteTypes; @@ -217,12 +208,4 @@ public boolean isRenderInternalMethodCallStubs() { public void setRenderInternalMethodCallStubs(boolean renderInternalMethodCallStubs) { this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; } - - public boolean isOpenUserCheckDialog() { - return openUserCheckDialog; - } - - public void setOpenUserCheckDialog(boolean openUserCheckDialog) { - this.openUserCheckDialog = openUserCheckDialog; - } } diff --git a/src/main/java/com/weirddev/testme/intellij/template/FileTemplateContext.java b/src/main/java/com/weirddev/testme/intellij/template/FileTemplateContext.java index b5bf4588..6e2668b2 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/FileTemplateContext.java +++ b/src/main/java/com/weirddev/testme/intellij/template/FileTemplateContext.java @@ -7,6 +7,7 @@ import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiPackage; import com.weirddev.testme.intellij.template.context.Language; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; /** * Date: 10/19/2016 @@ -24,8 +25,11 @@ public class FileTemplateContext { private final PsiDirectory targetDirectory; private final PsiClass srcClass; private final FileTemplateConfig fileTemplateConfig; + private final FileTemplateCustomization fileTemplateCustomization; - public FileTemplateContext(FileTemplateDescriptor fileTemplateDescriptor, Language language, Project project, String targetClass, PsiPackage targetPackage, Module srcModule, Module testModule, PsiDirectory targetDirectory, PsiClass srcClass, FileTemplateConfig fileTemplateConfig) { + public FileTemplateContext(FileTemplateDescriptor fileTemplateDescriptor, Language language, Project project, + String targetClass, PsiPackage targetPackage, Module srcModule, Module testModule, PsiDirectory targetDirectory, + PsiClass srcClass, FileTemplateConfig fileTemplateConfig, FileTemplateCustomization fileTemplateCustomization) { this.fileTemplateDescriptor = fileTemplateDescriptor; this.language = language; this.project = project; @@ -36,6 +40,7 @@ public FileTemplateContext(FileTemplateDescriptor fileTemplateDescriptor, Langua this.targetDirectory = targetDirectory; this.srcClass = srcClass; this.fileTemplateConfig = fileTemplateConfig; + this.fileTemplateCustomization = fileTemplateCustomization; } public Project getProject() { @@ -76,4 +81,8 @@ public Module getTestModule() { public FileTemplateConfig getFileTemplateConfig() { return fileTemplateConfig; } + + public FileTemplateCustomization getFileTemplateCustomization() { + return fileTemplateCustomization; + } } diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/Field.java b/src/main/java/com/weirddev/testme/intellij/template/context/Field.java index 3f5158f6..c57c8855 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/Field.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/Field.java @@ -100,7 +100,7 @@ private boolean buildAnnotatedByDI(PsiField psiField, PsiClass srcClass, TypeDic } - private boolean isOverriddenInChild(PsiField psiField, PsiClass srcClass) { + public static boolean isOverriddenInChild(PsiField psiField, PsiClass srcClass) { String srcQualifiedName = srcClass.getQualifiedName(); String fieldClsQualifiedName = psiField.getContainingClass()==null?null:psiField.getContainingClass().getQualifiedName(); return (srcQualifiedName!=null && fieldClsQualifiedName!=null && !srcQualifiedName.equals(fieldClsQualifiedName)) && srcClass.findFieldByName(psiField.getName(), false)!=null; diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockBuilder.java index cf2d62d4..16596540 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockBuilder.java @@ -14,11 +14,6 @@ public interface MockBuilder { */ boolean isMockable(Field field, Type testedClass); - /** - * true - field should mock - */ - boolean isMockable(Field field, Type testedClass, List userCheckedFieldsList); - /** * constructs an error message explaining why field cannot be mocked * @param prefix add prefix to message diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index 154a6d0f..526cec54 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -2,6 +2,7 @@ import com.intellij.openapi.diagnostic.Logger; import com.weirddev.testme.intellij.generator.TestBuilderUtil; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -54,7 +55,7 @@ public class MockitoMockBuilder implements MockBuilder{ } - private static final Set WRAPPER_TYPES = new HashSet<>(Arrays.asList( + public static final Set WRAPPER_TYPES = new HashSet<>(Arrays.asList( Class.class.getCanonicalName(), Boolean.class.getCanonicalName(), Byte.class.getCanonicalName(), @@ -75,12 +76,16 @@ public class MockitoMockBuilder implements MockBuilder{ private final String mockitoCoreVersion; private final Integer mockitoCoreMajorVersion; private final Integer mockitoCoreMinorVersion; + private final FileTemplateCustomization fileTemplateCustomization; - public MockitoMockBuilder(boolean isMockitoMockMakerInlineOn, boolean stubMockMethodCallsReturnValues, TestSubjectInspector testSubjectInspector, @Nullable String mockitoCoreVersion) { + public MockitoMockBuilder(boolean isMockitoMockMakerInlineOn, boolean stubMockMethodCallsReturnValues, + TestSubjectInspector testSubjectInspector, @Nullable String mockitoCoreVersion, + FileTemplateCustomization fileTemplateCustomization) { this.isMockitoMockMakerInlineOn = isMockitoMockMakerInlineOn; this.stubMockMethodCallsReturnValues = stubMockMethodCallsReturnValues; this.testSubjectInspector = testSubjectInspector; this.mockitoCoreVersion = mockitoCoreVersion; + this.fileTemplateCustomization = fileTemplateCustomization; if (mockitoCoreVersion != null) { Matcher matcher = SEMVER_PATTERN.matcher(mockitoCoreVersion); if (matcher.find()) { @@ -91,7 +96,6 @@ public MockitoMockBuilder(boolean isMockitoMockMakerInlineOn, boolean stubMockMe } this.mockitoCoreMajorVersion = null; this.mockitoCoreMinorVersion = null; - } private Integer safeParseInteger(String intStr) { @@ -116,26 +120,20 @@ public boolean isMockable(Field field) { /** * true - field can be mocked */ - @SuppressWarnings("unused") @Override - public boolean isMockable(Field field, Type testedClass, List userCheckedFieldsList) { - if (null != userCheckedFieldsList) { - return userCheckedFieldsList.contains(field.getName()); + public boolean isMockable(Field field, Type testedClass) { + boolean openUserCheckDialog = fileTemplateCustomization.isOpenUserCheckDialog(); + boolean isMockable; + if (openUserCheckDialog) { + isMockable = fileTemplateCustomization.getSelectedFieldNameList().contains(field.getName()); } else { - return isMockable(field, testedClass); + isMockable = !field.getType().isPrimitive() && !isWrapperType(field.getType()) + && (!field.getType().isFinal() || isMockitoMockMakerInlineOn) && !field.isOverridden() + && !field.getType().isArray() && !field.getType().isEnum() + && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass); } - } - - /** - * true - field can be mocked - */ - @Override - public boolean isMockable(Field field, Type testedClass) { - final boolean isMockable = !field.getType().isPrimitive() && !isWrapperType(field.getType()) - && (!field.getType().isFinal() || isMockitoMockMakerInlineOn) && !field.isOverridden() - && !field.getType().isArray() && !field.getType().isEnum() - && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass); - LOG.debug("field " + field.getType().getCanonicalName() + " " + field.getName() + " is mockable:" + isMockable); + LOG.debug( + "field " + field.getType().getCanonicalName() + " " + field.getName() + " is mockable:" + isMockable); return isMockable; } @@ -154,9 +152,9 @@ public boolean isMockable(Param param, Map defaultTypes) { * true - if any given field can be mocked */ @SuppressWarnings("unused") - public boolean hasMockable(List fields, Type testedClass, List userCheckedFieldsList) { + public boolean hasMockable(List fields, Type testedClass) { for (Field field : fields) { - if (isMockable(field, testedClass, userCheckedFieldsList)) { + if (isMockable(field, testedClass)) { return true; } } @@ -168,8 +166,8 @@ public boolean hasMockable(List fields, Type testedClass, List us * @param testedClass the tested class * @return true - if the tested class has mockable field */ - public boolean hasMocks(Type testedClass, List userCheckedFieldsList) { - return testSubjectInspector.hasAccessibleCtor(testedClass) && hasMockable(testedClass.getFields(), testedClass, userCheckedFieldsList); + public boolean hasMocks(Type testedClass) { + return testSubjectInspector.hasAccessibleCtor(testedClass) && hasMockable(testedClass.getFields(), testedClass); } /** diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java index fb4e8571..8c7bc389 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java @@ -1,6 +1,7 @@ package com.weirddev.testme.intellij.template.context; import com.intellij.openapi.diagnostic.Logger; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -14,11 +15,14 @@ public class PowerMockBuilder extends MockitoMockBuilder{ */ private final boolean renderInternalMethodCallStubs; + private final FileTemplateCustomization fileTemplateCustomization; + public PowerMockBuilder(boolean isMockitoMockMakerInlineOn, boolean stubMockMethodCallsReturnValues, TestSubjectInspector testSubjectInspector, @Nullable String mockitoCoreVersion, - boolean renderInternalMethodCallStubs) { - super(isMockitoMockMakerInlineOn, stubMockMethodCallsReturnValues, testSubjectInspector, mockitoCoreVersion); + boolean renderInternalMethodCallStubs, FileTemplateCustomization fileTemplateCustomization) { + super(isMockitoMockMakerInlineOn, stubMockMethodCallsReturnValues, testSubjectInspector, mockitoCoreVersion, fileTemplateCustomization); this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; + this.fileTemplateCustomization = fileTemplateCustomization; } /** @@ -37,22 +41,13 @@ public boolean hasInternalMethodCall(Method method, Type testedClass) { */ @Override public boolean isMockable(Field field, Type testedClass) { - final boolean isMockable = !field.getType().isPrimitive() && !isWrapperType(field.getType()) - && !field.isOverridden() && !field.getType().isArray() && !field.getType().isEnum() - && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass); - LOG.debug("field " + field.getType().getCanonicalName() + " " + field.getName() + " is mockable:" + isMockable); - return isMockable; - } - - /** - * true - field can be mocked - */ - @Override - public boolean isMockable(Field field, Type testedClass, List userCheckedFieldsList) { - if (null != userCheckedFieldsList) { - return userCheckedFieldsList.contains(field.getName()); + boolean openUserCheckDialog = fileTemplateCustomization.isOpenUserCheckDialog(); + if (openUserCheckDialog) { + return fileTemplateCustomization.getSelectedFieldNameList().contains(field.getName()); } else { - return isMockable(field, testedClass); + return !field.getType().isPrimitive() && !isWrapperType(field.getType()) && !field.isOverridden() + && !field.getType().isArray() && !field.getType().isEnum() + && !testSubjectInspector.isNotInjectedInDiClass(field, testedClass); } } diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java b/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java index 680f4444..9047e35d 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java @@ -60,18 +60,6 @@ public interface TestMeTemplateParams { */ String TestedClasspathJars = "TestedClasspathJars"; - /** - * user checked and selected mock field name list - * instance of {@link java.util.List} - */ - String USER_CHECKED_MOCK_FIELDS = "USER_CHECKED_MOCK_FIELDS"; - - /** - * user checked and selected test method id list - * instance of {@link java.util.List} - */ - String USER_CHECKED_TEST_METHODS = "USER_CHECKED_TEST_METHODS"; - /** * configured max recursion depth for object graph introspection * @see FileTemplateConfig#getMaxRecursionDepth() diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/TestSubjectInspector.java b/src/main/java/com/weirddev/testme/intellij/template/context/TestSubjectInspector.java index 070ffdce..cb622507 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/TestSubjectInspector.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/TestSubjectInspector.java @@ -1,6 +1,7 @@ package com.weirddev.testme.intellij.template.context; import com.intellij.openapi.diagnostic.Logger; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; import com.weirddev.testme.intellij.utils.ClassNameUtils; import org.jetbrains.annotations.Nullable; @@ -18,9 +19,10 @@ public class TestSubjectInspector private static final Logger LOG = Logger.getInstance(TestSubjectInspector.class.getName()); private static final Set SCALA_FUTURE_TYPES = Set.of("scala.concurrent.Future","scala.concurrent.impl.Promise"); private final boolean generateTestsForInheritedMethods; + private final FileTemplateCustomization fileTemplateCustomization; - public TestSubjectInspector(boolean generateTestsForInheritedMethods) { - + public TestSubjectInspector(boolean generateTestsForInheritedMethods, FileTemplateCustomization fileTemplateCustomization) { + this.fileTemplateCustomization = fileTemplateCustomization; this.generateTestsForInheritedMethods = generateTestsForInheritedMethods; } @@ -33,22 +35,16 @@ public boolean hasTestableInstanceMethod(List methods) { return false; } - /** - * @return true - method should test - */ - public boolean shouldBeTested(Method method, List userCheckedMethodIdList) { - if (null != userCheckedMethodIdList) { - return userCheckedMethodIdList.contains(method.getMethodId()); - } else { - return shouldBeTested(method); - } - } - /** * true - method should test */ public boolean shouldBeTested(Method method) { - return method.isTestable() && ( generateTestsForInheritedMethods || !method.isInherited()); + boolean openUserCheckDialog = fileTemplateCustomization.isOpenUserCheckDialog(); + if (openUserCheckDialog) { + return fileTemplateCustomization.getSelectedMethodIdList().contains(method.getMethodId()); + } else { + return method.isTestable() && (generateTestsForInheritedMethods || !method.isInherited()); + } } /** diff --git a/src/main/java/com/weirddev/testme/intellij/ui/classconfigdialog/CreateTestMeDialog.java b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java similarity index 53% rename from src/main/java/com/weirddev/testme/intellij/ui/classconfigdialog/CreateTestMeDialog.java rename to src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java index 5910165c..eaadf109 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/classconfigdialog/CreateTestMeDialog.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java @@ -1,4 +1,4 @@ -package com.weirddev.testme.intellij.ui.classconfigdialog; +package com.weirddev.testme.intellij.ui.customizedialog; import java.util.*; import java.util.List; @@ -7,9 +7,16 @@ import com.intellij.psi.*; import com.intellij.psi.util.InheritanceUtil; +import com.intellij.psi.util.PsiUtil; +import com.weirddev.testme.intellij.builder.MethodFactory; import com.weirddev.testme.intellij.common.utils.PsiMethodUtils; +import com.weirddev.testme.intellij.generator.MockBuilderFactory; +import com.weirddev.testme.intellij.template.FileTemplateContext; import com.weirddev.testme.intellij.template.TemplateRegistry; import com.weirddev.testme.intellij.template.context.*; +import com.weirddev.testme.intellij.utils.ClassNameUtils; +import com.weirddev.testme.intellij.utils.JavaPsiTreeUtils; +import com.weirddev.testme.intellij.utils.JavaTypeUtils; import org.jetbrains.annotations.NotNull; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; @@ -24,23 +31,18 @@ * * @author huangliang */ -public class CreateTestMeDialog extends DialogWrapper { +public class CustomizeTestDialog extends DialogWrapper { - private final Map templateCtxtParams; private final PsiClass myTargetClass; - private final String templateFileName; private final MemberSelectionTable myMethodsTable = new MemberSelectionTable(Collections.emptyList(), null); private final MemberSelectionTable myFieldsTable = new MemberSelectionTable(Collections.emptyList(), null); - private final List checkedFieldNameList = new ArrayList<>(); - private final List checkedMethodIdList = new ArrayList<>(); + private final FileTemplateContext fileTemplateContext; - - public CreateTestMeDialog(@NotNull Project project, @NotNull @NlsContexts.DialogTitle String title, - PsiClass targetClass, String templateFileName, Map templateCtxtParams) { + public CustomizeTestDialog(@NotNull Project project, @NotNull @NlsContexts.DialogTitle String title, + PsiClass targetClass, FileTemplateContext fileTemplateContext) { super(project, true); myTargetClass = targetClass; - this.templateCtxtParams = templateCtxtParams; - this.templateFileName = templateFileName; + this.fileTemplateContext = fileTemplateContext; setTitle(title); init(); } @@ -50,15 +52,16 @@ protected JComponent createCenterPanel() { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); - JLabel fieldLabel = new JLabel("Select Need Mocked Fields"); + JLabel fieldLabel = new JLabel("Mock fields:"); panel.add(fieldLabel); panel.add(ScrollPaneFactory.createScrollPane(myFieldsTable)); - JLabel methodLabel = new JLabel("Select Need Test Methods"); + JLabel methodLabel = new JLabel("Test Methods:"); panel.add(methodLabel); panel.add(ScrollPaneFactory.createScrollPane(myMethodsTable)); initExtractingClassMembers(); + return panel; } @@ -69,13 +72,8 @@ private void updateClassMockableFields() { Collection selectedMemberInfos = myFieldsTable.getSelectedMemberInfos(); List userCheckedMockableFieldsList = selectedMemberInfos.stream().map(e -> e.getMember().getName()).toList(); - Type classTypeObj = (Type)templateCtxtParams.get(TestMeTemplateParams.TESTED_CLASS); - for (Field field : classTypeObj.getFields()) { - if (userCheckedMockableFieldsList.contains(field.getName())) { - checkedFieldNameList.add(field.getName()); - } - } - templateCtxtParams.put(TestMeTemplateParams.USER_CHECKED_MOCK_FIELDS, checkedFieldNameList); + fileTemplateContext.getFileTemplateCustomization().getSelectedFieldNameList() + .addAll(userCheckedMockableFieldsList); } /** @@ -85,71 +83,48 @@ private void updateClassTestableMethods() { Collection selectedMemberInfos = myMethodsTable.getSelectedMemberInfos(); List testableMethodList = selectedMemberInfos.stream().map(e -> PsiMethodUtils.formatMethodId((PsiMethod)e.getMember())).toList(); - Type classTypeObj = (Type)templateCtxtParams.get(TestMeTemplateParams.TESTED_CLASS); - for (Method method : classTypeObj.getMethods()) { - if (testableMethodList.contains(method.getMethodId())) { - checkedMethodIdList.add(method.getMethodId()); - } - } - templateCtxtParams.put(TestMeTemplateParams.USER_CHECKED_TEST_METHODS, checkedMethodIdList); + fileTemplateContext.getFileTemplateCustomization().getSelectedMethodIdList().addAll(testableMethodList); } /** * init and extract class fields and methods for user to check */ public void initExtractingClassMembers() { - Set classes= InheritanceUtil.getSuperClasses(myTargetClass); - classes.add(myTargetClass); - - Type classTypeObj = (Type)templateCtxtParams.get(TestMeTemplateParams.TESTED_CLASS); - TestSubjectInspector testSubjectUtil = - (TestSubjectInspector)templateCtxtParams.get(TestMeTemplateParams.TestSubjectUtils); - MockBuilder templateMockBuilder = getTemplateMockBuilder(templateFileName); - - // build field mockable map, key = field name, value = true - if field mockable - Map fieldMockableMap = new HashMap<>(); - for (Field field : classTypeObj.getFields()) { - Boolean fieldMockable = templateMockBuilder.isMockable(field, classTypeObj); - fieldMockableMap.put(field.getName(), fieldMockable); - } - // build method testable map, key = method id, value = true - if method testable - Map methodTestableMap = new HashMap<>(); - for (Method method : classTypeObj.getMethods()) { - Boolean testable = testSubjectUtil.shouldBeTested(method); - methodTestableMap.put(method.getMethodId(), testable); + Set classes; + if (fileTemplateContext.getFileTemplateConfig().isGenerateTestsForInheritedMethods()) { + classes = InheritanceUtil.getSuperClasses(myTargetClass); + classes.add(myTargetClass); + } else { + classes = Collections.singleton(myTargetClass); } // init method table and field table List methodResult = new ArrayList<>(); - List fieldResult = new ArrayList<>(); for (PsiClass aClass : classes) { if (CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) continue; - initMethodsTable(aClass, methodResult, methodTestableMap); - initFieldsTable(aClass, fieldResult, fieldMockableMap); + initMethodsTable(aClass, methodResult); } + + List fieldResult = new ArrayList<>(); + initFieldsTable(myTargetClass, fieldResult, fileTemplateContext.getFileTemplateDescriptor().getDisplayName()); } /** - * get mock builder for template + * * @param templateFileName template name - * @return MockBuilder + * @return true - if final can be mocked */ - private MockBuilder getTemplateMockBuilder(String templateFileName) { - if (TemplateRegistry.JUNIT4_POWERMOCK_JAVA_TEMPLATE.equals(templateFileName)) { - return (PowerMockBuilder)templateCtxtParams.get(TestMeTemplateParams.PowerMockBuilder); - } else { - return (MockitoMockBuilder)templateCtxtParams.get(TestMeTemplateParams.MockitoMockBuilder); - } + private boolean canMockFinal(String templateFileName) { + return TemplateRegistry.JUNIT4_POWERMOCK_JAVA_TEMPLATE.equals(templateFileName); } - private void initMethodsTable(PsiClass myTargetClass, List result, Map methodTestableMap) { + private void initMethodsTable(PsiClass myTargetClass, List result) { Set selectedMethods = new HashSet<>(); MemberInfo.extractClassMembers(myTargetClass, result, member -> { if (!(member instanceof PsiMethod method)) return false; - String methodId = PsiMethodUtils.formatMethodId(method); - if (methodTestableMap.containsKey(methodId) && methodTestableMap.get(methodId)) { + if (shouldBeTested(method, myTargetClass)) { selectedMethods.add(member); return true; } @@ -163,12 +138,12 @@ private void initMethodsTable(PsiClass myTargetClass, List result, M myMethodsTable.setMemberInfos(result); } - private void initFieldsTable(PsiClass myTargetClass, List result, Map fieldMockableMap) { + private void initFieldsTable(PsiClass myTargetClass, List result, String templateFileName) { Set selectedFields = new HashSet<>(); MemberInfo.extractClassMembers(myTargetClass, result, member -> { if (!(member instanceof PsiField field)) return false; - if (fieldMockableMap.containsKey(field.getName()) && fieldMockableMap.get(field.getName())) { + if (isMockable(field, myTargetClass, templateFileName)) { selectedFields.add(member); return true; } @@ -194,4 +169,27 @@ protected void doOKAction() { super.doOKAction(); } + public boolean isMockable(PsiField psiField, PsiClass testedClass, String templateFileName) { + boolean overridden = Field.isOverriddenInChild(psiField, testedClass); + boolean isFinal = + psiField.getModifierList() != null && psiField.getModifierList().hasExplicitModifier(PsiModifier.FINAL); + boolean isPrimitive = psiField.getType() instanceof PsiPrimitiveType; + PsiClass psiClass = PsiUtil.resolveClassInType(psiField.getType()); + String canonicalText = JavaTypeUtils.resolveCanonicalName(psiClass, null); + boolean isArray = ClassNameUtils.isArray(canonicalText); + boolean isEnum = JavaPsiTreeUtils.resolveIfEnum(psiClass); + boolean isMockitoMockMakerInlineOn = MockBuilderFactory.isMockInline(fileTemplateContext); + boolean isWrapperType = MockitoMockBuilder.WRAPPER_TYPES.contains(canonicalText); + return !isPrimitive && !isWrapperType + && (canMockFinal(templateFileName) || !isFinal || isMockitoMockMakerInlineOn) && !overridden && !isArray + && !isEnum; + } + + /** + * true - method should test + */ + public boolean shouldBeTested(PsiMethod method, PsiClass psiClass) { + return MethodFactory.isTestable(method, psiClass); + } + } diff --git a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/FileTemplateCustomization.java b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/FileTemplateCustomization.java new file mode 100644 index 00000000..64ec1b03 --- /dev/null +++ b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/FileTemplateCustomization.java @@ -0,0 +1,35 @@ +package com.weirddev.testme.intellij.ui.customizedialog; + +import java.util.List; + +/** + * customization of user selections + * @author huangliang + */ +public class FileTemplateCustomization { + + private final List selectedFieldNameList; + + private final List selectedMethodIdList; + + private final boolean openUserCheckDialog; + + public FileTemplateCustomization(List selectedFieldNameList, List selectedMethodIdList, + boolean openUserCheckDialog) { + this.selectedFieldNameList = selectedFieldNameList; + this.selectedMethodIdList = selectedMethodIdList; + this.openUserCheckDialog = openUserCheckDialog; + } + + public List getSelectedFieldNameList() { + return selectedFieldNameList; + } + + public List getSelectedMethodIdList() { + return selectedMethodIdList; + } + + public boolean isOpenUserCheckDialog() { + return openUserCheckDialog; + } +} diff --git a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form index d068c31c..598272d4 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form +++ b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form @@ -47,7 +47,7 @@ - + diff --git a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java index c22ff7e2..753c736b 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.java @@ -36,7 +36,7 @@ public void persistState(TestMeConfig testMeConfig) { testMeConfig.setReformatCode(reformatCodeCheckBox.isSelected()); testMeConfig.setReplaceFullyQualifiedNames(replaceFullyQualifiedNamesCheckBox.isSelected()); testMeConfig.setRenderInternalMethodCallStubs(renderInternalMethodCallStubsBox.isSelected()); - testMeConfig.setOpenUserCheckDialog(openUserCheckDialogBox.isSelected()); + testMeConfig.setOpenCustomizeTestDialog(openUserCheckDialogBox.isSelected()); } } @@ -47,7 +47,7 @@ public void reset(TestMeConfig state) { reformatCodeCheckBox.setSelected(state.getReformatCode()); replaceFullyQualifiedNamesCheckBox.setSelected(state.getReplaceFullyQualifiedNames()); renderInternalMethodCallStubsBox.setSelected(state.isRenderInternalMethodCallStubs()); - openUserCheckDialogBox.setSelected(state.isOpenUserCheckDialog()); + openUserCheckDialogBox.setSelected(state.isOpenCustomizeTestDialog()); } } @@ -58,7 +58,7 @@ public boolean isDirty(TestMeConfig state) { reformatCodeCheckBox.isSelected() != state.getReformatCode() || replaceFullyQualifiedNamesCheckBox.isSelected() != state.getReplaceFullyQualifiedNames() || renderInternalMethodCallStubsBox.isSelected() != state.isRenderInternalMethodCallStubs() || - openUserCheckDialogBox.isSelected() != state.isOpenUserCheckDialog() + openUserCheckDialogBox.isSelected() != state.isOpenCustomizeTestDialog() ); } } diff --git a/src/main/resources/fileTemplates/testMeIncludes/TestMe macros.java.ft b/src/main/resources/fileTemplates/testMeIncludes/TestMe macros.java.ft index f74050a2..0d5c5ab1 100644 --- a/src/main/resources/fileTemplates/testMeIncludes/TestMe macros.java.ft +++ b/src/main/resources/fileTemplates/testMeIncludes/TestMe macros.java.ft @@ -57,7 +57,7 @@ ## #macro(renderMockedFields $hasMocks $testedClass) #foreach($field in $testedClass.fields) -#if($hasMocks && $mockBuilder.isMockable($field, $testedClass, $USER_CHECKED_MOCK_FIELDS)) +#if($hasMocks && $mockBuilder.isMockable($field, $testedClass)) @Mock $field.type.canonicalName $field.name; #elseif($mockBuilder.isMockExpected($field)) @@ -88,7 +88,7 @@ assertEquals(result#{if}($TestSubjectUtils.isJavaFuture($method.returnType)).get ## #macro(renderMockStubs $method $testedClass) #foreach($field in $testedClass.fields) -#if($mockBuilder.isMockable($field, $testedClass, $USER_CHECKED_MOCK_FIELDS)) +#if($mockBuilder.isMockable($field, $testedClass)) #foreach($fieldMethod in $field.type.methods) #if($fieldMethod.hasReturn() && $TestSubjectUtils.isMethodCalled($fieldMethod,$method)) when($field.name.${fieldMethod.name}($mockBuilder.buildMockArgsMatchers(${fieldMethod.methodParams},"Java"))).thenReturn($TestBuilder.renderReturnParam($method,$fieldMethod.returnType,"${fieldMethod.name}Response",$replacementTypes,$defaultTypeValues)); @@ -100,7 +100,7 @@ assertEquals(result#{if}($TestSubjectUtils.isJavaFuture($method.returnType)).get ## #macro(renderMockVerifies $method $testedClass) #foreach($field in $testedClass.fields) -#if($mockBuilder.isMockable($field, $testedClass, $USER_CHECKED_MOCK_FIELDS)) +#if($mockBuilder.isMockable($field, $testedClass)) #foreach($fieldMethod in $field.type.methods) #if(!$fieldMethod.hasReturn() && $TestSubjectUtils.isMethodCalled($fieldMethod,$method)) verify($field.name).${fieldMethod.name}($mockBuilder.buildMockArgsMatchers(${fieldMethod.methodParams},"Java")); diff --git a/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft index ec2f86e8..99ea0025 100644 --- a/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Groovy, JUnit4 & Mockito.groovy.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.groovy") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME} #end @@ -25,7 +25,7 @@ class ${CLASS_NAME} { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) +#if($TestSubjectUtils.shouldBeTested($method)) @Test void #renderTestMethodName($method.name)() { diff --git a/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft index 3c37bbe8..314590b1 100644 --- a/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Groovy, Spock & Mockito.groovy.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.groovy") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME} #end @@ -22,7 +22,7 @@ class ${CLASS_NAME} extends Specification { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) +#if($TestSubjectUtils.shouldBeTested($method)) def "test #renderTestMethodNameAsWords($method.name)"() { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft index 34d6fd31..d9c6d64a 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.java") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME}; #end @@ -26,7 +26,7 @@ public class ${CLASS_NAME} { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) +#if($TestSubjectUtils.shouldBeTested($method)) @Test public void #renderTestMethodName($method.name)() throws Exception { diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft index 2228e4be..95cff5c4 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.java") -#set($hasMocks=$PowerMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) +#set($hasMocks=$PowerMockBuilder.hasMocks($TESTED_CLASS)) #set($mockBuilder = $PowerMockBuilder) #if($PACKAGE_NAME) package ${PACKAGE_NAME}; @@ -38,7 +38,7 @@ public class ${CLASS_NAME} { #end #foreach($method in $TESTED_CLASS.methods) - #if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) + #if($TestSubjectUtils.shouldBeTested($method)) @Test public void #renderTestMethodName($method.name)() throws Exception { #if($hasMocks && $PowerMockBuilder.shouldStub($method, $TESTED_CLASS)) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft index 838b15c7..7744a90e 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.java") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME}; #end @@ -25,7 +25,7 @@ class ${CLASS_NAME} { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) +#if($TestSubjectUtils.shouldBeTested($method)) @Test void #renderTestMethodName($method.name)(){ diff --git a/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft b/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft index 25156e50..2f0541fd 100644 --- a/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft +++ b/src/main/resources/fileTemplates/testMeTests/Parameterized Groovy, Spock & Mockito.groovy.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.groovy") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME} #end @@ -22,7 +22,7 @@ class ${CLASS_NAME} extends Specification { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) +#if($TestSubjectUtils.shouldBeTested($method)) #set($paraTestComponents=$TestBuilder.buildPrameterizedTestComponents($method,$grReplacementTypesForReturn,$grReplacementTypes,$grDefaultTypeValues)) @Unroll diff --git a/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft b/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft index ac6b3a8a..f24e4c47 100644 --- a/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft +++ b/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft @@ -27,10 +27,10 @@ class ${CLASS_NAME} extends Specification #if($hasMocks) with Mockito#end{ "$StringUtils.removeSuffix($TESTED_CLASS.name,"$")" should { #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) +#if($TestSubjectUtils.shouldBeTested($method)) "#renderTestMethodNameAsWords($method.name)" in { -#if($hasMocks && $MockitoMockBuilder.shouldStub($method,$constructor,$scDefaultTypeValues)) +#if($MockitoMockBuilder.shouldStub($method,$constructor,$scDefaultTypeValues)) #scRenderMockStubs($method, $constructor) #end $TAB$TAB#scRenderMethodCall($method,$TESTED_CLASS) diff --git a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft index 50537077..7bd6df0d 100644 --- a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft @@ -1,5 +1,5 @@ #parse("TestMe macros.java") -#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS, $USER_CHECKED_MOCK_FIELDS)) +#set($hasMocks=$MockitoMockBuilder.hasMocks($TESTED_CLASS)) #if($PACKAGE_NAME) package ${PACKAGE_NAME}; #end @@ -25,7 +25,7 @@ public class ${CLASS_NAME} { } #end #foreach($method in $TESTED_CLASS.methods) -#if($TestSubjectUtils.shouldBeTested($method, $USER_CHECKED_TEST_METHODS)) +#if($TestSubjectUtils.shouldBeTested($method)) @Test public void #renderTestMethodName($method.name)(){ From f7e12489d06ab7b249d55ca4b2cade01249f3083 Mon Sep 17 00:00:00 2001 From: Yaron Yamin Date: Tue, 26 Mar 2024 08:59:09 +0200 Subject: [PATCH 16/38] test generator: avoid mocking field that is initialized inline. fix UT --- .../mockReturned/test/com/example/services/impl/FooTest.java | 1 + .../testJunit5/com/example/services/impl/FooTest.java | 1 + .../testTestNg/com/example/services/impl/FooTest.java | 1 + 3 files changed, 3 insertions(+) diff --git a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java index 88d1bd62..b639aab5 100644 --- a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java @@ -22,6 +22,7 @@ public class FooTest { FooFighter fooFighter; @Mock Supplier result; + @InjectMocks Foo foo; diff --git a/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java index 8327de76..7c34f6b5 100644 --- a/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java @@ -22,6 +22,7 @@ class FooTest { FooFighter fooFighter; @Mock Supplier result; + @InjectMocks Foo foo; diff --git a/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java index 61072b1f..cf2c559d 100644 --- a/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java @@ -22,6 +22,7 @@ public class FooTest { FooFighter fooFighter; @Mock Supplier result; + @InjectMocks Foo foo; From ece9a921363ea168a366770760c51a4bdce7f3d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Tue, 26 Mar 2024 15:00:04 +0800 Subject: [PATCH 17/38] update --- src/main/resources/fileTemplates/internal/velocity_implicit.vm | 2 -- .../fileTemplates/testMeTests/Specs2 & Mockito.scala.ft | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/resources/fileTemplates/internal/velocity_implicit.vm b/src/main/resources/fileTemplates/internal/velocity_implicit.vm index 79110fb9..18692f27 100644 --- a/src/main/resources/fileTemplates/internal/velocity_implicit.vm +++ b/src/main/resources/fileTemplates/internal/velocity_implicit.vm @@ -12,6 +12,4 @@ #* @vtlvariable name="CLASS_NAME" type="java.lang.String" *# #* @vtlvariable name="MockitoMockBuilder" type="com.weirddev.testme.intellij.template.context.MockitoMockBuilder" *# #* @vtlvariable name="PowerMockBuilder" type="com.weirddev.testme.intellij.template.context.PowerMockBuilder" *# -#* @vtlvariable name="USER_CHECKED_MOCK_FIELDS" type="java.util.List" *# -#* @vtlvariable name="USER_CHECKED_TEST_METHODS" type="java.util.List" *# #* /fileTemplates/testMeIncludes/*.ft *# diff --git a/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft b/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft index f24e4c47..f0c72761 100644 --- a/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft +++ b/src/main/resources/fileTemplates/testMeTests/Specs2 & Mockito.scala.ft @@ -30,7 +30,7 @@ class ${CLASS_NAME} extends Specification #if($hasMocks) with Mockito#end{ #if($TestSubjectUtils.shouldBeTested($method)) "#renderTestMethodNameAsWords($method.name)" in { -#if($MockitoMockBuilder.shouldStub($method,$constructor,$scDefaultTypeValues)) +#if($hasMocks && $MockitoMockBuilder.shouldStub($method,$constructor,$scDefaultTypeValues)) #scRenderMockStubs($method, $constructor) #end $TAB$TAB#scRenderMethodCall($method,$TESTED_CLASS) From a596d6266f11897c5fb14b3adbce4149ffb69cb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Tue, 26 Mar 2024 15:05:14 +0800 Subject: [PATCH 18/38] update --- .../intellij/template/context/MockitoMockBuilderTest.groovy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/test/groovy/com/weirddev/testme/intellij/template/context/MockitoMockBuilderTest.groovy b/src/test/groovy/com/weirddev/testme/intellij/template/context/MockitoMockBuilderTest.groovy index 5cad693a..8c3789ec 100644 --- a/src/test/groovy/com/weirddev/testme/intellij/template/context/MockitoMockBuilderTest.groovy +++ b/src/test/groovy/com/weirddev/testme/intellij/template/context/MockitoMockBuilderTest.groovy @@ -1,6 +1,6 @@ package com.weirddev.testme.intellij.template.context - +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization import org.mockito.Mock import org.mockito.MockitoAnnotations import spock.lang.Specification @@ -20,7 +20,7 @@ class MockitoMockBuilderTest extends Specification { @Unroll def "get Init Mocks Method where mockitoCoreVersion=#mockitoCoreVersion"() { given: - mockitoMockBuilder = new MockitoMockBuilder(false, false, testSubjectInspector, mockitoCoreVersion) + mockitoMockBuilder = new MockitoMockBuilder(false, false, testSubjectInspector, mockitoCoreVersion, new FileTemplateCustomization(new ArrayList(), new ArrayList(), false)) expect: mockitoMockBuilder.getInitMocksMethod() == expectedResult From 9716098e4f8c03a920e7b1e8c57e4a9780856203 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Tue, 26 Mar 2024 15:19:02 +0800 Subject: [PATCH 19/38] update --- .../ui/customizedialog/CustomizeTestDialog.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java index eaadf109..3e93ae76 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java @@ -49,19 +49,21 @@ public CustomizeTestDialog(@NotNull Project project, @NotNull @NlsContexts.Dialo @Override protected JComponent createCenterPanel() { + initExtractingClassMembers(); + JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); - JLabel fieldLabel = new JLabel("Mock fields:"); - panel.add(fieldLabel); - panel.add(ScrollPaneFactory.createScrollPane(myFieldsTable)); + if (myFieldsTable.getRowCount() > 0) { + JLabel fieldLabel = new JLabel("Mock fields:"); + panel.add(fieldLabel); + panel.add(ScrollPaneFactory.createScrollPane(myFieldsTable)); + } JLabel methodLabel = new JLabel("Test Methods:"); panel.add(methodLabel); panel.add(ScrollPaneFactory.createScrollPane(myMethodsTable)); - initExtractingClassMembers(); - return panel; } From 835ed7dee5a36651cfe5e76a07b80cb270134291 Mon Sep 17 00:00:00 2001 From: Yaron Yamin Date: Tue, 26 Mar 2024 10:01:15 +0200 Subject: [PATCH 20/38] test generator: avoid mocking field that is initialized inline. fix UT #2 --- .../testGroovy/com/example/services/impl/FooTest.groovy | 1 + .../testSpock/com/example/services/impl/FooTest.groovy | 1 + 2 files changed, 2 insertions(+) diff --git a/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy index 5cc6dc77..1b1a3de2 100644 --- a/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockReturned/testGroovy/com/example/services/impl/FooTest.groovy @@ -20,6 +20,7 @@ class FooTest { FooFighter fooFighter @Mock Supplier result + @InjectMocks Foo foo diff --git a/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy index 7ebb3014..8f0b5242 100644 --- a/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockReturned/testSpock/com/example/services/impl/FooTest.groovy @@ -19,6 +19,7 @@ class FooTest extends Specification { FooFighter fooFighter @Mock Supplier result + @InjectMocks Foo foo From cada60912be3a2b39fedbe8dddd91f1408ded710 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Tue, 26 Mar 2024 16:15:53 +0800 Subject: [PATCH 21/38] add specific type to Mockito argument matcher any(),and work for array types --- .../template/context/MockitoMockBuilder.java | 37 ++++++++----------- .../com/example/services/impl/FooTest.java | 2 +- .../com/example/services/impl/FooTest.groovy | 2 +- .../com/example/services/impl/FooTest.java | 2 +- .../com/example/services/impl/FooTest.groovy | 2 +- .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.groovy | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.groovy | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.groovy | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 12 +++--- .../com/example/services/impl/FooTest.groovy | 12 +++--- .../com/example/services/impl/FooTest.java | 12 +++--- .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.groovy | 2 + .../com/example/services/impl/FooTest.java | 2 + .../com/example/services/impl/FooTest.java | 2 + 30 files changed, 82 insertions(+), 43 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index 4708e107..23f7068d 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -227,31 +227,26 @@ public String buildMockArgsMatchers(List params,String language) { */ @NotNull private String deductMatcherTypeMethod(Param param, Language language) { - String matcherType; - if (param.getType().isVarargs()) { - matcherType = "anyVararg"; + Type type = param.getType(); + String matcherMethod = resolveMatcherMethod(type); + if (language == Language.Scala) { + return matcherMethod; } - else { - matcherType = TYPE_TO_ARG_MATCHERS.get(param.getType().getCanonicalName()); - } - if (matcherType == null) { - matcherType = "any"; - } - //todo support anyCollection(),anyMap(),anySet() and consider arrays - if (language != Language.Scala) { - matcherType += "()"; - } - // add specific type to any() - if( matcherType.equals("any()")){ - matcherType = addSpecificType(param.getType().getName()); + else if (!type.isPrimitive() && "any".equals(matcherMethod)) { + return matcherMethod + "("+ type.getCanonicalName()+(type.isArray()? "[]":"") +".class)"; + } else { + return matcherMethod+"()"; } - return matcherType; } - @SuppressWarnings("unused") - @Deprecated - public boolean shouldStub(Method testMethod, List testedClassFields) { - return callsMockMethod(testMethod, testedClassFields, Method::hasReturn, null); + private static String resolveMatcherMethod(Type type) { + if (type.isVarargs()) { + return "anyVararg"; + } else if(!type.isArray() && TYPE_TO_ARG_MATCHERS.containsKey(type.getCanonicalName())){ + return TYPE_TO_ARG_MATCHERS.get(type.getCanonicalName()); + } else { + return "any"; + } } String addSpecificType(String typeName) { diff --git a/testData/testMeGenerator/inheritance/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/inheritance/test/com/example/services/impl/FooTest.java index 73af8848..f1dab1c2 100644 --- a/testData/testMeGenerator/inheritance/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/inheritance/test/com/example/services/impl/FooTest.java @@ -25,7 +25,7 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighter.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); String result = foo.fight(new com.example.foes.Fire(), "foeName"); Assert.assertEquals("replaceMeWithExpectedResult", result); diff --git a/testData/testMeGenerator/inheritance/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/inheritance/testGroovy/com/example/services/impl/FooTest.groovy index 95da7602..813b36a8 100644 --- a/testData/testMeGenerator/inheritance/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/inheritance/testGroovy/com/example/services/impl/FooTest.groovy @@ -23,7 +23,7 @@ class FooTest { @Test void testFight() { - when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(fooFighter.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse") java.lang.String result = foo.fight(new com.example.foes.Fire(), "foeName") assert result == "replaceMeWithExpectedResult" diff --git a/testData/testMeGenerator/inheritanceIgnored/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/inheritanceIgnored/test/com/example/services/impl/FooTest.java index 5d4ae249..042293f1 100644 --- a/testData/testMeGenerator/inheritanceIgnored/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/inheritanceIgnored/test/com/example/services/impl/FooTest.java @@ -25,7 +25,7 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighter.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); String result = foo.fight(new com.example.foes.Fire(), "foeName"); Assert.assertEquals("replaceMeWithExpectedResult", result); diff --git a/testData/testMeGenerator/inheritanceIgnored/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/inheritanceIgnored/testGroovy/com/example/services/impl/FooTest.groovy index bdc059b8..4e7514ec 100644 --- a/testData/testMeGenerator/inheritanceIgnored/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/inheritanceIgnored/testGroovy/com/example/services/impl/FooTest.groovy @@ -23,7 +23,7 @@ class FooTest { @Test void testFight() { - when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(fooFighter.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse") java.lang.String result = foo.fight(new com.example.foes.Fire(), "foeName") assert result == "replaceMeWithExpectedResult" diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDependencyInjection/test/com/example/services/impl/FooTest.java index 273f9784..8ae91316 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/test/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDependencyInjection/testGroovy/com/example/services/impl/FooTest.groovy index 72035cca..fd764ef1 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testGroovy/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import org.junit.Test import org.junit.Before diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDependencyInjection/testJunit5/com/example/services/impl/FooTest.java index fe1ec6e8..d11790a9 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testJunit5/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDependencyInjection/testPowerMock/com/example/services/impl/FooTest.java index 9d5454f5..4ec047a0 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testPowerMock/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDependencyInjection/testTestNg/com/example/services/impl/FooTest.java index d452d686..c3b9f608 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testTestNg/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.mockito.InjectMocks; import org.mockito.Mock; diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithCtor/test/com/example/services/impl/FooTest.java index d169e6e6..544c9f83 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/test/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDiWithCtor/testGroovy/com/example/services/impl/FooTest.groovy index 1d764a22..5bc48044 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/testGroovy/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import org.junit.Test import org.junit.Before diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithCtor/testJunit5/com/example/services/impl/FooTest.java index 3a7788c0..dbbd5c07 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/testJunit5/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithCtor/testTestNg/com/example/services/impl/FooTest.java index 84e3fb27..bbee7002 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/testTestNg/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.mockito.InjectMocks; import org.mockito.Mock; diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithSetter/test/com/example/services/impl/FooTest.java index 273f9784..8ae91316 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/test/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDiWithSetter/testGroovy/com/example/services/impl/FooTest.groovy index 72035cca..fd764ef1 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/testGroovy/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import org.junit.Test import org.junit.Before diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithSetter/testJunit5/com/example/services/impl/FooTest.java index fe1ec6e8..d11790a9 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/testJunit5/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockFieldsInDiWithSetter/testTestNg/com/example/services/impl/FooTest.java index d452d686..c3b9f608 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/testTestNg/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.mockito.InjectMocks; import org.mockito.Mock; diff --git a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java index 58e98b82..f97062e9 100644 --- a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java @@ -2,7 +2,9 @@ import com.example.beans.ConvertedBean; import com.example.dependencies.Logger; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.FooFighter; import org.junit.Assert; import org.junit.Before; diff --git a/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java index 63aa281c..8e6e4e0c 100644 --- a/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/testJunit5/com/example/services/impl/FooTest.java @@ -2,7 +2,9 @@ import com.example.beans.ConvertedBean; import com.example.dependencies.Logger; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.FooFighter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; diff --git a/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java index 707ae6ce..12eb4552 100644 --- a/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/testTestNg/com/example/services/impl/FooTest.java @@ -2,7 +2,9 @@ import com.example.beans.ConvertedBean; import com.example.dependencies.Logger; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.FooFighter; import org.mockito.InjectMocks; import org.mockito.Mock; diff --git a/testData/testMeGenerator/renderInternalMethodCallStubs/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/renderInternalMethodCallStubs/testPowerMock/com/example/services/impl/FooTest.java index 0ff8229b..cee84562 100644 --- a/testData/testMeGenerator/renderInternalMethodCallStubs/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/renderInternalMethodCallStubs/testPowerMock/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; diff --git a/testData/testMeGenerator/renderInternalMethodCallStubsIgnored/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/renderInternalMethodCallStubsIgnored/testPowerMock/com/example/services/impl/FooTest.java index 9d5454f5..4ec047a0 100644 --- a/testData/testMeGenerator/renderInternalMethodCallStubsIgnored/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/renderInternalMethodCallStubsIgnored/testPowerMock/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; diff --git a/testData/testMeGenerator/variousFieldTypes/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/variousFieldTypes/test/com/example/services/impl/FooTest.java index 56563c8c..c014c6cf 100644 --- a/testData/testMeGenerator/variousFieldTypes/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/variousFieldTypes/test/com/example/services/impl/FooTest.java @@ -45,12 +45,12 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterProtected.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterDefault.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterPublic.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterFinal.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterStatic.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighter.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterProtected.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterDefault.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterPublic.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterFinal.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterStatic.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); when(innerOfPublicInnerClass.methodOfInnerClass()).thenReturn(new Foo().new PublicInnerClass().new InnerOfPublicInnerClass()); String result = foo.fight(new com.example.foes.Fire(), "foeName"); diff --git a/testData/testMeGenerator/variousFieldTypes/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/variousFieldTypes/testGroovy/com/example/services/impl/FooTest.groovy index 5f9d523c..ab2d2e50 100644 --- a/testData/testMeGenerator/variousFieldTypes/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/variousFieldTypes/testGroovy/com/example/services/impl/FooTest.groovy @@ -41,12 +41,12 @@ class FooTest { @Test void testFight() { - when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse") - when(fooFighterProtected.fight(any(Fire.class))).thenReturn("fightResponse") - when(fooFighterDefault.fight(any(Fire.class))).thenReturn("fightResponse") - when(fooFighterPublic.fight(any(Fire.class))).thenReturn("fightResponse") - when(fooFighterFinal.fight(any(Fire.class))).thenReturn("fightResponse") - when(fooFighterStatic.fight(any(Fire.class))).thenReturn("fightResponse") + when(fooFighter.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse") + when(fooFighterProtected.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse") + when(fooFighterDefault.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse") + when(fooFighterPublic.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse") + when(fooFighterFinal.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse") + when(fooFighterStatic.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse") when(innerOfPublicInnerClass.methodOfInnerClass()).thenReturn(new com.example.services.impl.Foo.PublicInnerClass.InnerOfPublicInnerClass(new com.example.services.impl.Foo.PublicInnerClass(new com.example.services.impl.Foo()))) java.lang.String result = foo.fight(new com.example.foes.Fire(), "foeName") diff --git a/testData/testMeGenerator/variousFieldTypes/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/variousFieldTypes/testPowerMock/com/example/services/impl/FooTest.java index 37d7dfd5..d568d92f 100644 --- a/testData/testMeGenerator/variousFieldTypes/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/variousFieldTypes/testPowerMock/com/example/services/impl/FooTest.java @@ -57,12 +57,12 @@ public void setUp() { @Test public void testFight() throws Exception { - when(fooFighter.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterProtected.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterDefault.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterPublic.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterFinal.fight(any(Fire.class))).thenReturn("fightResponse"); - when(fooFighterStatic.fight(any(Fire.class))).thenReturn("fightResponse"); + when(fooFighter.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterProtected.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterDefault.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterPublic.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterFinal.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); + when(fooFighterStatic.fight(any(com.example.foes.Fire.class))).thenReturn("fightResponse"); when(innerOfPublicInnerClass.methodOfInnerClass()).thenReturn(new Foo().new PublicInnerClass().new InnerOfPublicInnerClass()); String result = foo.fight(new com.example.foes.Fire(), "foeName"); verify(publicInnerClass).methodOfInnerClass(); diff --git a/testData/testMeGenerator/verifyMethodCall/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/verifyMethodCall/test/com/example/services/impl/FooTest.java index d169e6e6..544c9f83 100644 --- a/testData/testMeGenerator/verifyMethodCall/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/verifyMethodCall/test/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; diff --git a/testData/testMeGenerator/verifyMethodCall/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/verifyMethodCall/testGroovy/com/example/services/impl/FooTest.groovy index 1d764a22..5bc48044 100644 --- a/testData/testMeGenerator/verifyMethodCall/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/verifyMethodCall/testGroovy/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import org.junit.Test import org.junit.Before diff --git a/testData/testMeGenerator/verifyMethodCall/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/verifyMethodCall/testJunit5/com/example/services/impl/FooTest.java index 3a7788c0..dbbd5c07 100644 --- a/testData/testMeGenerator/verifyMethodCall/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/verifyMethodCall/testJunit5/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; diff --git a/testData/testMeGenerator/verifyMethodCall/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/verifyMethodCall/testTestNg/com/example/services/impl/FooTest.java index 84e3fb27..bbee7002 100644 --- a/testData/testMeGenerator/verifyMethodCall/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/verifyMethodCall/testTestNg/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.mockito.InjectMocks; import org.mockito.Mock; From a12d3702e871af4bfa7f0a85a41d788e763c324e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Tue, 26 Mar 2024 17:10:43 +0800 Subject: [PATCH 22/38] add specific type to Mockito argument matcher any(),and work for array types --- .../testSpock/com/example/services/impl/FooTest.groovy | 2 ++ .../testSpock/com/example/services/impl/FooTest.groovy | 2 ++ .../testSpock/com/example/services/impl/FooTest.groovy | 2 ++ 3 files changed, 6 insertions(+) diff --git a/testData/testMeGenerator/mockFieldsInDependencyInjection/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDependencyInjection/testSpock/com/example/services/impl/FooTest.groovy index 640be037..6f83d057 100644 --- a/testData/testMeGenerator/mockFieldsInDependencyInjection/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDependencyInjection/testSpock/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import spock.lang.* import org.mockito.InjectMocks diff --git a/testData/testMeGenerator/mockFieldsInDiWithCtor/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDiWithCtor/testSpock/com/example/services/impl/FooTest.groovy index 2f89cc4c..6efaba8c 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithCtor/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDiWithCtor/testSpock/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import spock.lang.* import org.mockito.InjectMocks diff --git a/testData/testMeGenerator/mockFieldsInDiWithSetter/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/mockFieldsInDiWithSetter/testSpock/com/example/services/impl/FooTest.groovy index 640be037..6f83d057 100644 --- a/testData/testMeGenerator/mockFieldsInDiWithSetter/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/mockFieldsInDiWithSetter/testSpock/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import spock.lang.* import org.mockito.InjectMocks From 04e45614e022b78d8dcfe9792b674635f2724e46 Mon Sep 17 00:00:00 2001 From: Yaron Yamin Date: Tue, 26 Mar 2024 22:34:33 +0200 Subject: [PATCH 23/38] testme popup - replace powermock icon --- src/main/resources/icons/powermock.png | Bin 618 -> 1423 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/src/main/resources/icons/powermock.png b/src/main/resources/icons/powermock.png index 735bd7ad58577af8e0345f2210d3db6cb1e58c2b..1bf22eace4f877d1cd883fc74682795fb66893ef 100644 GIT binary patch literal 1423 zcmV;A1#tR_P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D1tdvCK~zXf%~We_ zQ)L)F-#Mr4w$pa&x{a}0*SWH>xJzVL1`KA1h+M=41td-wW)71sMv-Jj&=5=(gMmRZ zFoG};(K#R^+y)O-HdObbIx1~mKQ5pKf=g;?@FVFj(=REK8 z9_+sc&+{m_8jVKk(dU1{6OsN78#iv8(A(QzO_G8Uk%;_p!-fs%VzKzF&1S14Ns{*a z{Sh%SF;<|u5JJ9(Rb%n5gw)p7<^%$KHOu;uPIq4&2n0mw=?ZOO;gmIHWo79qmC7cQ z$&T6W_IV&?Kdd=Ysq|L3{4wC+b=;t7IuTs2vsx{p?(Uv7EX#_Z4cPtry}7NeZ6~&D z*}C@N!NVT{m1o&N?#ReUD!7ve90J^$^zfEH@Kiz!21C@QO`EGIN_@j)dQcxeehhtm zeab_J4o%c*wV#2O%N)-)f;&g7R$BwO(jUAdOby|wgh(Wk^yK8EynFZVR&g8`J{=4A za{0cm_pb!!ra%U6SuEBa7{;|T3{wVTO2f1e#x2C@bQVAs28V`*><)*cB78gsLZOh! z&YrZu>v30hbevqq@z^vD<9`L+%UPaJ2?pBba+Uu+RpS;yQ4|fe%WGYpojZ>-H8pi=G}n*t9G{1A{1OiFcd$S}VzF30hWa}&Nqn$oTteUr(yUhN zQjSBHGc&Uq=Fgvh3q~|_(W6i((${U@zU_Q)-_p`TWo2hA;dpK$3@OR6f%g$2Mxm|+ z!dnTGG(E^0myoEasD23C0fg8L9%Hx4<*~-;)63^%Wo4}oQ!wcL^}Ty{LqH$m>Q&A9 ziWwDg!99pk;yCK%_&}}K>t9C1#-0LxNbnQ?N1&Gi#_62K`g|%dGq0_!O`y?SYj19D zKB`u$YX$}kUz$uN41}&uOia+5OvA}3DXIFG7cJa%u&u2}U0+Yh3((51Q+85a6Vkx&-ztZYAXH2mJb1PF>~X!vNZ+wF{^)Z&N*k^LS zlPDFfp5dWxp+x!`Nr^8p^tJ7R=$MP_=qSPb(j_9Js0Rq)dXu^PC)Q>gboc7Itv{b1 z1for&SND&X^f!#W(J>}cdw z9Qoo!3Gv4{zrP2=0_GTH#_@~&#wxIVu1b~po=&G*0YRRZ&$(%NZb75%re^8hd-^es d{7-;kzX6?+aMMg-li~mX002ovPDHLkV1mrBv)BLt literal 618 zcmV-w0+s!VP)Px%BuPX;R5(v#WIzMozki>>$;p}V>C>kQK0dwBS^r?%I1GjQGs7y--J!a zjvWDuy?*odzo>{Xn2irGHZ`@`@7}%hz~8@rG1S2f`}y-{1v@)?$IqWXBiY&6mm@1= ztgmmly?gf_6>PRlpFVYlzP^6u^A|7wOG=2tUGweRH(4$&uE!ufj3DRZbE1rl^q=L+ zm-W1Q{iXtB2)bbe4FGxL!-o%385tQDfBXL9ILMF>A3pvU5a0*92(JOKFaRlp*^KOh z&!4|sz-a)o=9@Qfrt%92&ieoVKLffq7=wdD{~H?{-`KKciv}z#kTrwEN=nN97nc-+ zrCC^57(mhc;^nLVT%4RY;34bg=JEf_moH#N$Oc45$Nul1IN`+qfB!80{rd-&7ZMcc zU}tBq1cw2L$jQn3TU}Gl6dV)`HvkknH8oW$4ULS$!$QLte0;ntm1U-agCVOLlC1dul@EG!uM`g*_`(A9#&044~dK?ZUWRn>Lj}R#wJRSXlT3x*-H}8=>3?0Qa{5FFQ&wg#Z8m07*qoM6N<$ Eg8O$RSO5S3 From 530a95983c09f6c1e29a1064cbf9ac54d2309eaa Mon Sep 17 00:00:00 2001 From: Yaron Yamin Date: Tue, 26 Mar 2024 23:25:28 +0200 Subject: [PATCH 24/38] version bump v6.3.0 --- gradle.properties | 2 +- src/main/resources/META-INF/plugin.xml | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/gradle.properties b/gradle.properties index 9d77d88c..4d95e5a0 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ group = 'com.weirddev.testme' -version = 6.2.0 +version = 6.3.0 #jvmTargetVersion = 1.8 jvmTargetVersion = 17 diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml index a4eecc19..c8e6658f 100644 --- a/src/main/resources/META-INF/plugin.xml +++ b/src/main/resources/META-INF/plugin.xml @@ -1,7 +1,7 @@ com.weirddev.testme TestMe - 6.2.0 + 6.3.0 WeirdDev Features: Complete Release Notes listing ]]> From cecc9a5f5e683f2c804eb46d232ee7eae624fe45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Thu, 28 Mar 2024 10:21:40 +0800 Subject: [PATCH 25/38] update --- .../template/context/MockitoMockBuilder.java | 11 +++- .../template/context/PowerMockBuilder.java | 21 +------ .../customizedialog/CustomizeTestDialog.java | 63 ++++++++----------- 3 files changed, 37 insertions(+), 58 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index 332399e4..831400a9 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -131,13 +131,22 @@ public boolean isMockable(Field field, Type testedClass) { if (openUserCheckDialog) { isMockable = fileTemplateCustomization.getSelectedFieldNameList().contains(field.getName()); } else { - isMockable = isMockableCommonChecks(field, testedClass) && (!field.getType().isFinal() || isMockitoMockMakerInlineOn); + isMockable = isMockableCommonChecks(field, testedClass) && isMockableByMockFramework(field); } LOG.debug( "field " + field.getType().getCanonicalName() + " " + field.getName() + " is mockable:" + isMockable); return isMockable; } + /** + * + * @param field field to mock + * @return true if field can be mocked in mock framework + */ + protected boolean isMockableByMockFramework(Field field) { + return !field.getType().isFinal() || isMockitoMockMakerInlineOn; + } + /** * checks if field in testedClass can be mocked. evaluates conditions common to all currently supported mock frameworks * @return true if input field in testedClass can be mocked diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java index 6a11692d..f3f3a344 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/PowerMockBuilder.java @@ -1,28 +1,20 @@ package com.weirddev.testme.intellij.template.context; -import com.intellij.openapi.diagnostic.Logger; import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; import org.jetbrains.annotations.Nullable; -import java.util.List; - public class PowerMockBuilder extends MockitoMockBuilder{ - private static final Logger LOG = Logger.getInstance(PowerMockBuilder.class.getName()); - /** * true when render internal method call option is opted-in on custom settings */ private final boolean renderInternalMethodCallStubs; - private final FileTemplateCustomization fileTemplateCustomization; - public PowerMockBuilder(boolean isMockitoMockMakerInlineOn, boolean stubMockMethodCallsReturnValues, TestSubjectInspector testSubjectInspector, @Nullable String mockitoCoreVersion, boolean renderInternalMethodCallStubs, FileTemplateCustomization fileTemplateCustomization) { super(isMockitoMockMakerInlineOn, stubMockMethodCallsReturnValues, testSubjectInspector, mockitoCoreVersion, fileTemplateCustomization); this.renderInternalMethodCallStubs = renderInternalMethodCallStubs; - this.fileTemplateCustomization = fileTemplateCustomization; } /** @@ -39,17 +31,8 @@ public boolean hasInternalMethodCall(Method method, Type testedClass) { /** * true - field can be mocked */ - @Override - public boolean isMockable(Field field, Type testedClass) { - boolean openUserCheckDialog = fileTemplateCustomization.isOpenUserCheckDialog(); - boolean isMockable; - if (openUserCheckDialog) { - isMockable = fileTemplateCustomization.getSelectedFieldNameList().contains(field.getName()); - } else { - isMockable = isMockableCommonChecks(field, testedClass);; - } - LOG.debug("field " + field.getType().getCanonicalName() + " " + field.getName() + " is mockable:" + isMockable); - return isMockable; + protected boolean isMockableByMockFramework(Field field) { + return true; } } diff --git a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java index 3e93ae76..cc802718 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java @@ -43,14 +43,14 @@ public CustomizeTestDialog(@NotNull Project project, @NotNull @NlsContexts.Dialo super(project, true); myTargetClass = targetClass; this.fileTemplateContext = fileTemplateContext; + initMethodsTable(myTargetClass); + initFieldsTable(myTargetClass, fileTemplateContext.getFileTemplateDescriptor().getDisplayName()); setTitle(title); init(); } @Override protected JComponent createCenterPanel() { - initExtractingClassMembers(); - JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); @@ -88,30 +88,6 @@ private void updateClassTestableMethods() { fileTemplateContext.getFileTemplateCustomization().getSelectedMethodIdList().addAll(testableMethodList); } - /** - * init and extract class fields and methods for user to check - */ - public void initExtractingClassMembers() { - Set classes; - if (fileTemplateContext.getFileTemplateConfig().isGenerateTestsForInheritedMethods()) { - classes = InheritanceUtil.getSuperClasses(myTargetClass); - classes.add(myTargetClass); - } else { - classes = Collections.singleton(myTargetClass); - } - - // init method table and field table - List methodResult = new ArrayList<>(); - for (PsiClass aClass : classes) { - if (CommonClassNames.JAVA_LANG_OBJECT.equals(aClass.getQualifiedName())) - continue; - initMethodsTable(aClass, methodResult); - } - - List fieldResult = new ArrayList<>(); - initFieldsTable(myTargetClass, fieldResult, fileTemplateContext.getFileTemplateDescriptor().getDisplayName()); - } - /** * * @param templateFileName template name @@ -121,27 +97,37 @@ private boolean canMockFinal(String templateFileName) { return TemplateRegistry.JUNIT4_POWERMOCK_JAVA_TEMPLATE.equals(templateFileName); } - private void initMethodsTable(PsiClass myTargetClass, List result) { + private List initMethodsTable(PsiClass myTargetClass) { + Set classes = new HashSet<>(); + InheritanceUtil.getSuperClasses(myTargetClass, classes, false); + classes.add(myTargetClass); + Set selectedMethods = new HashSet<>(); - MemberInfo.extractClassMembers(myTargetClass, result, member -> { - if (!(member instanceof PsiMethod method)) + List result = new ArrayList<>(); + // init method table and field table + for (PsiClass aClass : classes) { + MemberInfo.extractClassMembers(aClass, result, member -> { + if (!(member instanceof PsiMethod method)) + return false; + if (shouldBeTested(method, myTargetClass)) { + selectedMethods.add(member); + return true; + } return false; - if (shouldBeTested(method, myTargetClass)) { - selectedMethods.add(member); - return true; - } - return false; - }, false); + }, false); + } for (MemberInfo each : result) { each.setChecked(selectedMethods.contains(each.getMember())); } myMethodsTable.setMemberInfos(result); + return result; } - private void initFieldsTable(PsiClass myTargetClass, List result, String templateFileName) { + private List initFieldsTable(PsiClass myTargetClass, String templateFileName) { Set selectedFields = new HashSet<>(); + List result = new ArrayList<>(); MemberInfo.extractClassMembers(myTargetClass, result, member -> { if (!(member instanceof PsiField field)) return false; @@ -157,6 +143,7 @@ private void initFieldsTable(PsiClass myTargetClass, List result, St } myFieldsTable.setMemberInfos(result); + return result; } @Override @@ -171,7 +158,7 @@ protected void doOKAction() { super.doOKAction(); } - public boolean isMockable(PsiField psiField, PsiClass testedClass, String templateFileName) { + private boolean isMockable(PsiField psiField, PsiClass testedClass, String templateFileName) { boolean overridden = Field.isOverriddenInChild(psiField, testedClass); boolean isFinal = psiField.getModifierList() != null && psiField.getModifierList().hasExplicitModifier(PsiModifier.FINAL); @@ -190,7 +177,7 @@ public boolean isMockable(PsiField psiField, PsiClass testedClass, String templa /** * true - method should test */ - public boolean shouldBeTested(PsiMethod method, PsiClass psiClass) { + private boolean shouldBeTested(PsiMethod method, PsiClass psiClass) { return MethodFactory.isTestable(method, psiClass); } From 08b0634a347e38465a2a4f4fc3e10050e97462c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Thu, 28 Mar 2024 15:24:50 +0800 Subject: [PATCH 26/38] add specific type to Mockito argument matcher any(),and work for array types --- .../intellij/template/context/MockitoMockBuilder.java | 6 ++++-- .../test/com/example/services/impl/FooTest.java | 1 - 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index 7f6aba61..c66847d8 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -263,8 +263,10 @@ private static String resolveMatcherMethod(Type type) { } } - String addSpecificType(String typeName) { - return StringUtils.isNotEmpty(typeName) ? "any("+typeName+".class)" : "any()"; + @SuppressWarnings("unused") + @Deprecated + public boolean shouldStub(Method testMethod, List testedClassFields) { + return callsMockMethod(testMethod, testedClassFields, Method::hasReturn, null); } /** * true - if should stub tested method diff --git a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java index fe253734..84ae0da5 100644 --- a/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/mockReturned/test/com/example/services/impl/FooTest.java @@ -1,7 +1,6 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; -import com.example.dependencies.Logger; import com.example.foes.Fear; import com.example.foes.Fire; import com.example.foes.Ice; From 70cc5170572d707febb75a37c46d808c5b9812ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Thu, 28 Mar 2024 15:29:14 +0800 Subject: [PATCH 27/38] add specific type to Mockito argument matcher any-- remove unused method --- .../testme/intellij/template/context/MockitoMockBuilder.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java index c66847d8..c8af7031 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/MockitoMockBuilder.java @@ -2,7 +2,6 @@ import com.intellij.openapi.diagnostic.Logger; import com.weirddev.testme.intellij.generator.TestBuilderUtil; -import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; From d812b31272284da609cd9c7ceec9abe3f070df34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Fri, 29 Mar 2024 10:13:39 +0800 Subject: [PATCH 28/38] add fileTemplateCustomization integrationTest --- .../TestMeGeneratorJunit4PowerMockTest.java | 18 ++++++ .../generator/TestMeGeneratorJunit4Test.java | 18 ++++++ .../generator/TestMeGeneratorJunit5Test.java | 19 +++++++ .../generator/TestMeGeneratorSpecs2Test.java | 17 ++++++ .../generator/TestMeGeneratorSpockTest.java | 19 +++++++ .../generator/TestMeGeneratorTestBase.java | 17 +++++- .../generator/TestMeGeneratorTestNgTest.java | 19 +++++++ .../customizedialog/CustomizeTestDialog.java | 11 ++-- .../src/com/example/services/impl/Foo.java | 40 ++++++++++++++ .../com/example/services/impl/FooTest.java | 46 ++++++++++++++++ .../com/example/services/impl/FooTest.groovy | 42 ++++++++++++++ .../com/example/services/impl/FooTest.java | 46 ++++++++++++++++ .../com/example/services/impl/FooTest.java | 55 +++++++++++++++++++ .../com/example/services/impl/FooTest.groovy | 42 ++++++++++++++ .../com/example/services/impl/FooTest.java | 46 ++++++++++++++++ 15 files changed, 447 insertions(+), 8 deletions(-) create mode 100644 testData/testMeGenerator/fileTemplateCustomization/src/com/example/services/impl/Foo.java create mode 100644 testData/testMeGenerator/fileTemplateCustomization/test/com/example/services/impl/FooTest.java create mode 100644 testData/testMeGenerator/fileTemplateCustomization/testGroovy/com/example/services/impl/FooTest.groovy create mode 100644 testData/testMeGenerator/fileTemplateCustomization/testJunit5/com/example/services/impl/FooTest.java create mode 100644 testData/testMeGenerator/fileTemplateCustomization/testPowerMock/com/example/services/impl/FooTest.java create mode 100644 testData/testMeGenerator/fileTemplateCustomization/testSpock/com/example/services/impl/FooTest.groovy create mode 100644 testData/testMeGenerator/fileTemplateCustomization/testTestNg/com/example/services/impl/FooTest.java diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4PowerMockTest.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4PowerMockTest.java index d9f0ee76..a4f06848 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4PowerMockTest.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4PowerMockTest.java @@ -5,6 +5,10 @@ import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.TemplateRegistry; import com.weirddev.testme.intellij.template.context.Language; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; + +import java.util.ArrayList; +import java.util.List; public class TestMeGeneratorJunit4PowerMockTest extends TestMeGeneratorTestBase { @@ -39,4 +43,18 @@ public void testRenderInternalMethodCallStubsIgnored() { doTest(new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState())); } + public void testFileTemplateCustomization() { + final TestMeConfig testMeConfig = new TestMeConfig(); + testMeConfig.setOpenCustomizeTestDialog(true); + final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); + List selectedFieldNameList = new ArrayList<>(); + selectedFieldNameList.add("result"); + selectedFieldNameList.add("techFighter"); + List selectedMethodIdList = new ArrayList<>(); + selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + final FileTemplateCustomization customization = + new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); + doTest(fileTemplateConfig, customization); + } + } diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4Test.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4Test.java index 8c56b7d3..69b11e47 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4Test.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4Test.java @@ -5,6 +5,10 @@ import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.TemplateRegistry; import com.weirddev.testme.intellij.template.context.Language; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; + +import java.util.ArrayList; +import java.util.List; /** * Date: 10/20/2016 @@ -192,6 +196,20 @@ public void testMockFieldsInDiWithCtor() { doTest(new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState())); } + public void testFileTemplateCustomization() { + final TestMeConfig testMeConfig = new TestMeConfig(); + testMeConfig.setOpenCustomizeTestDialog(true); + final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); + List selectedFieldNameList = new ArrayList<>(); + selectedFieldNameList.add("result"); + selectedFieldNameList.add("techFighter"); + List selectedMethodIdList = new ArrayList<>(); + selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + final FileTemplateCustomization customization = + new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); + doTest(fileTemplateConfig, customization); + } + //todo TC - use static init method when constructor not available // TODO TC different test target dir diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit5Test.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit5Test.java index 0e610be1..a35656cd 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit5Test.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit5Test.java @@ -1,9 +1,14 @@ package com.weirddev.testme.intellij.generator; +import com.weirddev.testme.intellij.configuration.TestMeConfig; import com.weirddev.testme.intellij.configuration.TestMeConfigPersistent; import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.TemplateRegistry; import com.weirddev.testme.intellij.template.context.Language; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; + +import java.util.ArrayList; +import java.util.List; /** * Date: 13/12/2016 @@ -48,4 +53,18 @@ public void testMockFieldsInDiWithSetter() { public void testMockFieldsInDiWithCtor() { doTest(new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState())); } + + public void testFileTemplateCustomization() { + final TestMeConfig testMeConfig = new TestMeConfig(); + testMeConfig.setOpenCustomizeTestDialog(true); + final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); + List selectedFieldNameList = new ArrayList<>(); + selectedFieldNameList.add("result"); + selectedFieldNameList.add("techFighter"); + List selectedMethodIdList = new ArrayList<>(); + selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + final FileTemplateCustomization customization = + new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); + doTest(fileTemplateConfig, customization); + } } diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpecs2Test.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpecs2Test.java index fcbec256..785527b3 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpecs2Test.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpecs2Test.java @@ -13,8 +13,11 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.LightProjectDescriptor; +import com.weirddev.testme.intellij.configuration.TestMeConfig; +import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.TemplateRegistry; import com.weirddev.testme.intellij.template.context.Language; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -95,6 +98,20 @@ private void doTestWithDefaults() { doTest(true,true,true, TestMeGeneratorJunit4Test.MIN_PERCENT_OF_EXCESSIVE_SETTERS_TO_PREFER_DEFAULT_CTOR, true, true); } + public void testFileTemplateCustomization() { + final TestMeConfig testMeConfig = new TestMeConfig(); + testMeConfig.setOpenCustomizeTestDialog(true); + final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); + List selectedFieldNameList = new ArrayList<>(); + selectedFieldNameList.add("result"); + selectedFieldNameList.add("techFighter"); + List selectedMethodIdList = new ArrayList<>(); + selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + final FileTemplateCustomization customization = + new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); + doTest(fileTemplateConfig, customization); + } + /** * see https://github.com/JetBrains/intellij-scala/blob/9198f8fb5b93d2ff142a65e320b812fc92cc0830/scala/scala-impl/test/org/jetbrains/plugins/scala/LightScalaTestCase.scala */ diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpockTest.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpockTest.java index ba169610..64c74b23 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpockTest.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpockTest.java @@ -1,9 +1,14 @@ package com.weirddev.testme.intellij.generator; +import com.weirddev.testme.intellij.configuration.TestMeConfig; import com.weirddev.testme.intellij.configuration.TestMeConfigPersistent; import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.TemplateRegistry; import com.weirddev.testme.intellij.template.context.Language; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; + +import java.util.ArrayList; +import java.util.List; /** * Date: 24/02/2017 @@ -41,4 +46,18 @@ public void testMockFieldsInDiWithSetter() { public void testMockFieldsInDiWithCtor() { doTest(new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState())); } + + public void testFileTemplateCustomization() { + final TestMeConfig testMeConfig = new TestMeConfig(); + testMeConfig.setOpenCustomizeTestDialog(true); + final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); + List selectedFieldNameList = new ArrayList<>(); + selectedFieldNameList.add("result"); + selectedFieldNameList.add("techFighter"); + List selectedMethodIdList = new ArrayList<>(); + selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + final FileTemplateCustomization customization = + new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); + doTest(fileTemplateConfig, customization); + } } diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java index ebf01894..5daaf0e3 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestBase.java @@ -77,6 +77,10 @@ protected void doTest(FileTemplateConfig fileTemplateConfig) { doTest("com.example.services.impl", "Foo", "FooTest", fileTemplateConfig); } + protected void doTest(FileTemplateConfig fileTemplateConfig, FileTemplateCustomization fileTemplateCustomization) { + doTest("com.example.services.impl", "Foo", "FooTest", fileTemplateConfig, fileTemplateCustomization); + } + protected void doTest(final String packageName, String testSubjectClassName, final String expectedTestClassName, final boolean reformatCode, final boolean optimizeImports, final boolean replaceFqn, final boolean ignoreUnusedProperties, final int minPercentOfExcessiveSettersToPreferDefaultCtor, boolean stubMockMethodCallsReturnValues) { final TestMeConfig testMeConfig = new TestMeConfig(); testMeConfig.setGenerateTestsForInheritedMethods(true); @@ -96,7 +100,13 @@ protected void doTest(final String packageName, String testSubjectClassName, fin doTest(packageName, testSubjectClassName, expectedTestClassName, fileTemplateConfig); } - protected void doTest(final String packageName, String testSubjectClassName, final String expectedTestClassName, final FileTemplateConfig fileTemplateConfig) { + protected void doTest(final String packageName, String testSubjectClassName, final String expectedTestClassName, + final FileTemplateConfig fileTemplateConfig) { + doTest(packageName, testSubjectClassName, expectedTestClassName, fileTemplateConfig, null); + } + + protected void doTest(final String packageName, String testSubjectClassName, final String expectedTestClassName, + final FileTemplateConfig fileTemplateConfig, final FileTemplateCustomization fileTemplateCustomization) { if (!testEnabled) { System.out.println(expectedTestClassExtension+ " idea plugin disabled. Skipping test"); return; @@ -105,6 +115,9 @@ protected void doTest(final String packageName, String testSubjectClassName, fin final PsiDirectory srcDir = fooClass.getContainingFile().getContainingDirectory(); final PsiPackage targetPackage = JavaDirectoryService.getInstance().getPackage(srcDir); + FileTemplateCustomization customization = null != fileTemplateCustomization ? fileTemplateCustomization + : new FileTemplateCustomization(new ArrayList<>(), new ArrayList<>(), false); + CommandProcessor.getInstance().executeCommand(getProject(), () -> { myFixture.openFileInEditor(fooClass.getContainingFile().getVirtualFile()); @@ -116,7 +129,7 @@ protected void doTest(final String packageName, String testSubjectClassName, fin srcDir, fooClass, fileTemplateConfig, - new FileTemplateCustomization(new ArrayList<>(), new ArrayList<>(), false))); + customization)); System.out.println("result:"+result); verifyGeneratedTest(packageName, expectedTestClassName); }, CodeInsightBundle.message("intention.create.test"), this); diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestNgTest.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestNgTest.java index 8130f3fc..ca602204 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestNgTest.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestNgTest.java @@ -1,9 +1,14 @@ package com.weirddev.testme.intellij.generator; +import com.weirddev.testme.intellij.configuration.TestMeConfig; import com.weirddev.testme.intellij.configuration.TestMeConfigPersistent; import com.weirddev.testme.intellij.template.FileTemplateConfig; import com.weirddev.testme.intellij.template.TemplateRegistry; import com.weirddev.testme.intellij.template.context.Language; +import com.weirddev.testme.intellij.ui.customizedialog.FileTemplateCustomization; + +import java.util.ArrayList; +import java.util.List; /** * Date: 23/05/2017 @@ -49,4 +54,18 @@ public void testMockFieldsInDiWithCtor() { doTest(new FileTemplateConfig(TestMeConfigPersistent.getInstance().getState())); } + public void testFileTemplateCustomization() { + final TestMeConfig testMeConfig = new TestMeConfig(); + testMeConfig.setOpenCustomizeTestDialog(true); + final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); + List selectedFieldNameList = new ArrayList<>(); + selectedFieldNameList.add("result"); + selectedFieldNameList.add("techFighter"); + List selectedMethodIdList = new ArrayList<>(); + selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + final FileTemplateCustomization customization = + new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); + doTest(fileTemplateConfig, customization); + } + } \ No newline at end of file diff --git a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java index cc802718..19625c77 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java @@ -33,18 +33,17 @@ */ public class CustomizeTestDialog extends DialogWrapper { - private final PsiClass myTargetClass; - private final MemberSelectionTable myMethodsTable = new MemberSelectionTable(Collections.emptyList(), null); - private final MemberSelectionTable myFieldsTable = new MemberSelectionTable(Collections.emptyList(), null); + private final MemberSelectionTable myMethodsTable; + private final MemberSelectionTable myFieldsTable; private final FileTemplateContext fileTemplateContext; public CustomizeTestDialog(@NotNull Project project, @NotNull @NlsContexts.DialogTitle String title, PsiClass targetClass, FileTemplateContext fileTemplateContext) { super(project, true); - myTargetClass = targetClass; this.fileTemplateContext = fileTemplateContext; - initMethodsTable(myTargetClass); - initFieldsTable(myTargetClass, fileTemplateContext.getFileTemplateDescriptor().getDisplayName()); + myMethodsTable = new MemberSelectionTable(initMethodsTable(targetClass), null); + myFieldsTable = new MemberSelectionTable( + initFieldsTable(targetClass, fileTemplateContext.getFileTemplateDescriptor().getDisplayName()), null); setTitle(title); init(); } diff --git a/testData/testMeGenerator/fileTemplateCustomization/src/com/example/services/impl/Foo.java b/testData/testMeGenerator/fileTemplateCustomization/src/com/example/services/impl/Foo.java new file mode 100644 index 00000000..42fe2f41 --- /dev/null +++ b/testData/testMeGenerator/fileTemplateCustomization/src/com/example/services/impl/Foo.java @@ -0,0 +1,40 @@ +package com.example.services.impl; + +import com.example.beans.ConvertedBean; +import java.util.function.Supplier; +import com.example.dependencies.Logger; +import com.example.foes.Fear; +import com.example.foes.Fire; +import com.example.foes.Ice; +import com.example.warriers.TechFighter; +import com.example.dependencies.Logger; +import javax.inject.Singleton; +import javax.inject.Inject; + +@Singleton +public class Foo{ + + @Inject + private TechFighter techFighter; + + @Inject + private Supplier result; + + private Logger logger; + + public String fight(Fire withFire,String foeName) { + logger.trace("logger should not mocked when it not selected to mock"); + logger.trace("this method should be tested when it selected to test"); + techFighter.initSelfArming("gun"); + String fail = techFighter.fight(withFire); + ConvertedBean convertedBean = techFighter.surrender(new Fear(), new Ice(), 666); + convertedBean.setSomeNum(result.get()); + return "returning response from dependency "+ fail + " " + convertedBean.getMyString(); + } + + public String fightSuccess(Fire withFire) { + logger.trace("this method should not be tested when it not selected to test"); + String success = techFighter.fight(withFire); + return "returning response from dependency " + success; + } +} diff --git a/testData/testMeGenerator/fileTemplateCustomization/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/fileTemplateCustomization/test/com/example/services/impl/FooTest.java new file mode 100644 index 00000000..fd88aa53 --- /dev/null +++ b/testData/testMeGenerator/fileTemplateCustomization/test/com/example/services/impl/FooTest.java @@ -0,0 +1,46 @@ +package com.example.services.impl; + +import com.example.beans.ConvertedBean; +import com.example.foes.Fire; +import com.example.warriers.TechFighter; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.function.Supplier; + +import static org.mockito.Mockito.*; + +/** + * created by TestMe integration test on MMXVI + */ +public class FooTest { + @Mock + TechFighter techFighter; + @Mock + Supplier result; + + @InjectMocks + Foo foo; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testFight() throws Exception { + when(techFighter.fight(any())).thenReturn("fightResponse"); + when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(result.get()).thenReturn(Integer.valueOf(0)); + + String result = foo.fight(new Fire(), "foeName"); + verify(techFighter).initSelfArming(anyString()); + Assert.assertEquals("replaceMeWithExpectedResult", result); + } +} + +//Generated with love by TestMe :) Please raise issues & feature requests at: https://weirddev.com/forum#!/testme \ No newline at end of file diff --git a/testData/testMeGenerator/fileTemplateCustomization/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/fileTemplateCustomization/testGroovy/com/example/services/impl/FooTest.groovy new file mode 100644 index 00000000..a8c52b38 --- /dev/null +++ b/testData/testMeGenerator/fileTemplateCustomization/testGroovy/com/example/services/impl/FooTest.groovy @@ -0,0 +1,42 @@ +package com.example.services.impl + +import com.example.beans.ConvertedBean +import com.example.foes.Fire +import com.example.warriers.TechFighter +import org.junit.Test +import org.junit.Before +import org.mockito.InjectMocks +import org.mockito.Mock +import org.mockito.MockitoAnnotations + +import java.util.function.Supplier +import static org.mockito.Mockito.* + +/** created by TestMe integration test on MMXVI */ +class FooTest { + @Mock + TechFighter techFighter + @Mock + Supplier result + + @InjectMocks + Foo foo + + @Before + void setUp() { + MockitoAnnotations.initMocks(this) + } + + @Test + void testFight() { + when(techFighter.fight(any())).thenReturn("fightResponse") + when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(result.get()).thenReturn(0) + + String result = foo.fight(new Fire(), "foeName") + verify(techFighter).initSelfArming(anyString()) + assert result == "replaceMeWithExpectedResult" + } +} + +//Generated with love by TestMe :) Please raise issues & feature requests at: https://weirddev.com/forum#!/testme \ No newline at end of file diff --git a/testData/testMeGenerator/fileTemplateCustomization/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/fileTemplateCustomization/testJunit5/com/example/services/impl/FooTest.java new file mode 100644 index 00000000..d66ace41 --- /dev/null +++ b/testData/testMeGenerator/fileTemplateCustomization/testJunit5/com/example/services/impl/FooTest.java @@ -0,0 +1,46 @@ +package com.example.services.impl; + +import com.example.beans.ConvertedBean; +import com.example.foes.Fire; +import com.example.warriers.TechFighter; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import java.util.function.Supplier; + +import static org.mockito.Mockito.*; + +/** + * created by TestMe integration test on MMXVI + */ +class FooTest { + @Mock + TechFighter techFighter; + @Mock + Supplier result; + + @InjectMocks + Foo foo; + + @BeforeEach + void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + void testFight() { + when(techFighter.fight(any())).thenReturn("fightResponse"); + when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(result.get()).thenReturn(Integer.valueOf(0)); + + String result = foo.fight(new Fire(), "foeName"); + verify(techFighter).initSelfArming(anyString()); + Assertions.assertEquals("replaceMeWithExpectedResult", result); + } +} + +//Generated with love by TestMe :) Please raise issues & feature requests at: https://weirddev.com/forum#!/testme \ No newline at end of file diff --git a/testData/testMeGenerator/fileTemplateCustomization/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/fileTemplateCustomization/testPowerMock/com/example/services/impl/FooTest.java new file mode 100644 index 00000000..c403a509 --- /dev/null +++ b/testData/testMeGenerator/fileTemplateCustomization/testPowerMock/com/example/services/impl/FooTest.java @@ -0,0 +1,55 @@ +package com.example.services.impl; + +import com.example.beans.ConvertedBean; +import com.example.foes.Fire; +import com.example.warriers.TechFighter; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.function.Supplier; + +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.*; + +/** + * created by TestMe integration test on MMXVI + */ +@RunWith(PowerMockRunner.class) +@PrepareForTest({Foo.class}) +@PowerMockIgnore("javax.management.*") +public class FooTest { + @Mock + TechFighter techFighter; + @Mock + Supplier result; + + @InjectMocks + Foo foo; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testFight() throws Exception { + when(techFighter.fight(any())).thenReturn("fightResponse"); + when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(result.get()).thenReturn(Integer.valueOf(0)); + String result = foo.fight(new Fire(), "foeName"); + verify(techFighter).initSelfArming(anyString()); + Assert.assertEquals("replaceMeWithExpectedResult", result); + + } +} + +//Generated with love by TestMe :) Please raise issues & feature requests at: https://weirddev.com/forum#!/testme \ No newline at end of file diff --git a/testData/testMeGenerator/fileTemplateCustomization/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/fileTemplateCustomization/testSpock/com/example/services/impl/FooTest.groovy new file mode 100644 index 00000000..71653bfd --- /dev/null +++ b/testData/testMeGenerator/fileTemplateCustomization/testSpock/com/example/services/impl/FooTest.groovy @@ -0,0 +1,42 @@ +package com.example.services.impl + +import com.example.beans.ConvertedBean +import com.example.foes.Fire +import com.example.warriers.TechFighter +import spock.lang.* +import org.mockito.InjectMocks +import org.mockito.Mock +import org.mockito.MockitoAnnotations + +import java.util.function.Supplier +import static org.mockito.Mockito.* + +/** created by TestMe integration test on MMXVI */ +class FooTest extends Specification { + @Mock + TechFighter techFighter + @Mock + Supplier result + + @InjectMocks + Foo foo + + def setup() { + MockitoAnnotations.initMocks(this) + } + + def "test fight"() { + given: + when(techFighter.fight(any())).thenReturn("fightResponse") + when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(result.get()).thenReturn(0) + + when: + String result = foo.fight(new Fire(), "foeName") + + then: + result == "replaceMeWithExpectedResult" + } +} + +//Generated with love by TestMe :) Please raise issues & feature requests at: https://weirddev.com/forum#!/testme \ No newline at end of file diff --git a/testData/testMeGenerator/fileTemplateCustomization/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/fileTemplateCustomization/testTestNg/com/example/services/impl/FooTest.java new file mode 100644 index 00000000..9669ff74 --- /dev/null +++ b/testData/testMeGenerator/fileTemplateCustomization/testTestNg/com/example/services/impl/FooTest.java @@ -0,0 +1,46 @@ +package com.example.services.impl; + +import com.example.beans.ConvertedBean; +import com.example.foes.Fire; +import com.example.warriers.TechFighter; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.function.Supplier; + +import static org.mockito.Mockito.*; + +/** + * created by TestMe integration test on MMXVI + */ +public class FooTest { + @Mock + TechFighter techFighter; + @Mock + Supplier result; + + @InjectMocks + Foo foo; + + @BeforeMethod + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testFight() { + when(techFighter.fight(any())).thenReturn("fightResponse"); + when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(result.get()).thenReturn(Integer.valueOf(0)); + + String result = foo.fight(new Fire(), "foeName"); + verify(techFighter).initSelfArming(anyString()); + Assert.assertEquals(result, "replaceMeWithExpectedResult"); + } +} + +//Generated with love by TestMe :) Please raise issues & feature requests at: https://weirddev.com/forum#!/testme \ No newline at end of file From f25d16b3b75ee343ec6d2c6ac014fd1834416175 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Fri, 29 Mar 2024 10:55:11 +0800 Subject: [PATCH 29/38] add fileTemplateCustomization integrationTest --- .../intellij/ui/customizedialog/CustomizeTestDialog.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java index 19625c77..be95df68 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java @@ -119,8 +119,6 @@ private List initMethodsTable(PsiClass myTargetClass) { for (MemberInfo each : result) { each.setChecked(selectedMethods.contains(each.getMember())); } - - myMethodsTable.setMemberInfos(result); return result; } @@ -141,7 +139,6 @@ private List initFieldsTable(PsiClass myTargetClass, String template each.setChecked(selectedFields.contains(each.getMember())); } - myFieldsTable.setMemberInfos(result); return result; } From 98ec86143485a9f1a229f98930b632d860bb4200 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Fri, 29 Mar 2024 11:11:42 +0800 Subject: [PATCH 30/38] add fileTemplateCustomization integrationTest --- .../test/com/example/services/impl/FooTest.java | 6 ++++-- .../testGroovy/com/example/services/impl/FooTest.groovy | 6 ++++-- .../testJunit5/com/example/services/impl/FooTest.java | 6 ++++-- .../testPowerMock/com/example/services/impl/FooTest.java | 6 ++++-- .../testSpock/com/example/services/impl/FooTest.groovy | 6 ++++-- .../testTestNg/com/example/services/impl/FooTest.java | 6 ++++-- 6 files changed, 24 insertions(+), 12 deletions(-) diff --git a/testData/testMeGenerator/fileTemplateCustomization/test/com/example/services/impl/FooTest.java b/testData/testMeGenerator/fileTemplateCustomization/test/com/example/services/impl/FooTest.java index fd88aa53..8ae91316 100644 --- a/testData/testMeGenerator/fileTemplateCustomization/test/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/fileTemplateCustomization/test/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; @@ -33,8 +35,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/fileTemplateCustomization/testGroovy/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/fileTemplateCustomization/testGroovy/com/example/services/impl/FooTest.groovy index a8c52b38..fd764ef1 100644 --- a/testData/testMeGenerator/fileTemplateCustomization/testGroovy/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/fileTemplateCustomization/testGroovy/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import org.junit.Test import org.junit.Before @@ -29,8 +31,8 @@ class FooTest { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) String result = foo.fight(new Fire(), "foeName") diff --git a/testData/testMeGenerator/fileTemplateCustomization/testJunit5/com/example/services/impl/FooTest.java b/testData/testMeGenerator/fileTemplateCustomization/testJunit5/com/example/services/impl/FooTest.java index d66ace41..d11790a9 100644 --- a/testData/testMeGenerator/fileTemplateCustomization/testJunit5/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/fileTemplateCustomization/testJunit5/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -33,8 +35,8 @@ void setUp() { @Test void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); diff --git a/testData/testMeGenerator/fileTemplateCustomization/testPowerMock/com/example/services/impl/FooTest.java b/testData/testMeGenerator/fileTemplateCustomization/testPowerMock/com/example/services/impl/FooTest.java index c403a509..4ec047a0 100644 --- a/testData/testMeGenerator/fileTemplateCustomization/testPowerMock/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/fileTemplateCustomization/testPowerMock/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.junit.Assert; import org.junit.Before; @@ -42,8 +44,8 @@ public void setUp() { @Test public void testFight() throws Exception { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); verify(techFighter).initSelfArming(anyString()); diff --git a/testData/testMeGenerator/fileTemplateCustomization/testSpock/com/example/services/impl/FooTest.groovy b/testData/testMeGenerator/fileTemplateCustomization/testSpock/com/example/services/impl/FooTest.groovy index 71653bfd..6f83d057 100644 --- a/testData/testMeGenerator/fileTemplateCustomization/testSpock/com/example/services/impl/FooTest.groovy +++ b/testData/testMeGenerator/fileTemplateCustomization/testSpock/com/example/services/impl/FooTest.groovy @@ -1,7 +1,9 @@ package com.example.services.impl import com.example.beans.ConvertedBean +import com.example.foes.Fear import com.example.foes.Fire +import com.example.foes.Ice import com.example.warriers.TechFighter import spock.lang.* import org.mockito.InjectMocks @@ -27,8 +29,8 @@ class FooTest extends Specification { def "test fight"() { given: - when(techFighter.fight(any())).thenReturn("fightResponse") - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse") + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean(myString: "myString", someNum: 0)) when(result.get()).thenReturn(0) when: diff --git a/testData/testMeGenerator/fileTemplateCustomization/testTestNg/com/example/services/impl/FooTest.java b/testData/testMeGenerator/fileTemplateCustomization/testTestNg/com/example/services/impl/FooTest.java index 9669ff74..c3b9f608 100644 --- a/testData/testMeGenerator/fileTemplateCustomization/testTestNg/com/example/services/impl/FooTest.java +++ b/testData/testMeGenerator/fileTemplateCustomization/testTestNg/com/example/services/impl/FooTest.java @@ -1,7 +1,9 @@ package com.example.services.impl; import com.example.beans.ConvertedBean; +import com.example.foes.Fear; import com.example.foes.Fire; +import com.example.foes.Ice; import com.example.warriers.TechFighter; import org.mockito.InjectMocks; import org.mockito.Mock; @@ -33,8 +35,8 @@ public void setUp() { @Test public void testFight() { - when(techFighter.fight(any())).thenReturn("fightResponse"); - when(techFighter.surrender(any(), any(), anyInt())).thenReturn(new ConvertedBean()); + when(techFighter.fight(any(Fire.class))).thenReturn("fightResponse"); + when(techFighter.surrender(any(Fear.class), any(Ice.class), anyInt())).thenReturn(new ConvertedBean()); when(result.get()).thenReturn(Integer.valueOf(0)); String result = foo.fight(new Fire(), "foeName"); From b7ac9e1217420df67f1e0404861128a19efa2cfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Fri, 29 Mar 2024 11:30:48 +0800 Subject: [PATCH 31/38] add fileTemplateCustomization integrationTest --- .../com/example/services/impl/FooTest.scala | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 testData/testMeGenerator/fileTemplateCustomization/testSpecs2/com/example/services/impl/FooTest.scala diff --git a/testData/testMeGenerator/fileTemplateCustomization/testSpecs2/com/example/services/impl/FooTest.scala b/testData/testMeGenerator/fileTemplateCustomization/testSpecs2/com/example/services/impl/FooTest.scala new file mode 100644 index 00000000..1aae3952 --- /dev/null +++ b/testData/testMeGenerator/fileTemplateCustomization/testSpecs2/com/example/services/impl/FooTest.scala @@ -0,0 +1,20 @@ +package com.example.services.impl + +import com.example.foes.Fire +import org.specs2.mutable.Specification + +/** created by TestMe integration test on MMXVI */ +class FooTest extends Specification { + val foo = new Foo() + + "Foo" should { + + "fight" in { + val result = foo.fight(new Fire(), "foeName") + result === "replaceMeWithExpectedResult" + } + + } +} + +//Generated with love by TestMe :) Please raise issues & feature requests at: https://weirddev.com/forum#!/testme \ No newline at end of file From 68e6fd326b1a6d22f9257181d57b8482289feba0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Fri, 29 Mar 2024 11:47:10 +0800 Subject: [PATCH 32/38] add fileTemplateCustomization integrationTest --- .../generator/TestMeGeneratorSpecs2Test.java | 14 ------------- .../com/example/services/impl/FooTest.scala | 20 ------------------- 2 files changed, 34 deletions(-) delete mode 100644 testData/testMeGenerator/fileTemplateCustomization/testSpecs2/com/example/services/impl/FooTest.scala diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpecs2Test.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpecs2Test.java index 785527b3..186943e6 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpecs2Test.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpecs2Test.java @@ -98,20 +98,6 @@ private void doTestWithDefaults() { doTest(true,true,true, TestMeGeneratorJunit4Test.MIN_PERCENT_OF_EXCESSIVE_SETTERS_TO_PREFER_DEFAULT_CTOR, true, true); } - public void testFileTemplateCustomization() { - final TestMeConfig testMeConfig = new TestMeConfig(); - testMeConfig.setOpenCustomizeTestDialog(true); - final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); - List selectedFieldNameList = new ArrayList<>(); - selectedFieldNameList.add("result"); - selectedFieldNameList.add("techFighter"); - List selectedMethodIdList = new ArrayList<>(); - selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); - final FileTemplateCustomization customization = - new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); - doTest(fileTemplateConfig, customization); - } - /** * see https://github.com/JetBrains/intellij-scala/blob/9198f8fb5b93d2ff142a65e320b812fc92cc0830/scala/scala-impl/test/org/jetbrains/plugins/scala/LightScalaTestCase.scala */ diff --git a/testData/testMeGenerator/fileTemplateCustomization/testSpecs2/com/example/services/impl/FooTest.scala b/testData/testMeGenerator/fileTemplateCustomization/testSpecs2/com/example/services/impl/FooTest.scala deleted file mode 100644 index 1aae3952..00000000 --- a/testData/testMeGenerator/fileTemplateCustomization/testSpecs2/com/example/services/impl/FooTest.scala +++ /dev/null @@ -1,20 +0,0 @@ -package com.example.services.impl - -import com.example.foes.Fire -import org.specs2.mutable.Specification - -/** created by TestMe integration test on MMXVI */ -class FooTest extends Specification { - val foo = new Foo() - - "Foo" should { - - "fight" in { - val result = foo.fight(new Fire(), "foeName") - result === "replaceMeWithExpectedResult" - } - - } -} - -//Generated with love by TestMe :) Please raise issues & feature requests at: https://weirddev.com/forum#!/testme \ No newline at end of file From 69426526ab23a32b0635974b1f058888fa4a8b10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Mon, 1 Apr 2024 12:45:29 +0800 Subject: [PATCH 33/38] file template customization bug fix --- .../customizedialog/CustomizeTestDialog.java | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java index be95df68..636eb774 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java +++ b/src/main/java/com/weirddev/testme/intellij/ui/customizedialog/CustomizeTestDialog.java @@ -155,19 +155,29 @@ protected void doOKAction() { } private boolean isMockable(PsiField psiField, PsiClass testedClass, String templateFileName) { + boolean isPrimitive = psiField.getType() instanceof PsiPrimitiveType; + // make a direct return if isPrimitive, because PsiUtil.resolveClassInType(psiField.getType()) returns null + if (isPrimitive) { + return false; + } boolean overridden = Field.isOverriddenInChild(psiField, testedClass); + if (overridden) { + return false; + } boolean isFinal = psiField.getModifierList() != null && psiField.getModifierList().hasExplicitModifier(PsiModifier.FINAL); - boolean isPrimitive = psiField.getType() instanceof PsiPrimitiveType; + boolean isMockitoMockMakerInlineOn = MockBuilderFactory.isMockInline(fileTemplateContext); + if (!(canMockFinal(templateFileName) || !isFinal || isMockitoMockMakerInlineOn)) { + return false; + } PsiClass psiClass = PsiUtil.resolveClassInType(psiField.getType()); - String canonicalText = JavaTypeUtils.resolveCanonicalName(psiClass, null); - boolean isArray = ClassNameUtils.isArray(canonicalText); boolean isEnum = JavaPsiTreeUtils.resolveIfEnum(psiClass); - boolean isMockitoMockMakerInlineOn = MockBuilderFactory.isMockInline(fileTemplateContext); - boolean isWrapperType = MockitoMockBuilder.WRAPPER_TYPES.contains(canonicalText); - return !isPrimitive && !isWrapperType - && (canMockFinal(templateFileName) || !isFinal || isMockitoMockMakerInlineOn) && !overridden && !isArray - && !isEnum; + if (isEnum) { + return false; + } + String canonicalText = JavaTypeUtils.resolveCanonicalName(psiClass, null); + return (null != canonicalText) && !MockitoMockBuilder.WRAPPER_TYPES.contains(canonicalText) + && !ClassNameUtils.isArray(canonicalText); } /** From 439bd0628ad8eea0fdf8c112e1cb74b713d0f195 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E9=BB=84=E4=BA=AE?= Date: Mon, 1 Apr 2024 13:05:54 +0800 Subject: [PATCH 34/38] test modify --- .../generator/TestMeGeneratorJunit4PowerMockTest.java | 7 ++----- .../intellij/generator/TestMeGeneratorJunit4Test.java | 7 ++----- .../intellij/generator/TestMeGeneratorJunit5Test.java | 7 ++----- .../intellij/generator/TestMeGeneratorSpockTest.java | 7 ++----- .../intellij/generator/TestMeGeneratorTestNgTest.java | 7 ++----- 5 files changed, 10 insertions(+), 25 deletions(-) diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4PowerMockTest.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4PowerMockTest.java index a4f06848..e37c4c0c 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4PowerMockTest.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4PowerMockTest.java @@ -47,11 +47,8 @@ public void testFileTemplateCustomization() { final TestMeConfig testMeConfig = new TestMeConfig(); testMeConfig.setOpenCustomizeTestDialog(true); final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); - List selectedFieldNameList = new ArrayList<>(); - selectedFieldNameList.add("result"); - selectedFieldNameList.add("techFighter"); - List selectedMethodIdList = new ArrayList<>(); - selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + List selectedFieldNameList = List.of("result", "techFighter"); + List selectedMethodIdList = List.of("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); final FileTemplateCustomization customization = new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); doTest(fileTemplateConfig, customization); diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4Test.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4Test.java index 69b11e47..56378e74 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4Test.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit4Test.java @@ -200,11 +200,8 @@ public void testFileTemplateCustomization() { final TestMeConfig testMeConfig = new TestMeConfig(); testMeConfig.setOpenCustomizeTestDialog(true); final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); - List selectedFieldNameList = new ArrayList<>(); - selectedFieldNameList.add("result"); - selectedFieldNameList.add("techFighter"); - List selectedMethodIdList = new ArrayList<>(); - selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + List selectedFieldNameList = List.of("result", "techFighter"); + List selectedMethodIdList = List.of("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); final FileTemplateCustomization customization = new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); doTest(fileTemplateConfig, customization); diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit5Test.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit5Test.java index a35656cd..9d724068 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit5Test.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorJunit5Test.java @@ -58,11 +58,8 @@ public void testFileTemplateCustomization() { final TestMeConfig testMeConfig = new TestMeConfig(); testMeConfig.setOpenCustomizeTestDialog(true); final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); - List selectedFieldNameList = new ArrayList<>(); - selectedFieldNameList.add("result"); - selectedFieldNameList.add("techFighter"); - List selectedMethodIdList = new ArrayList<>(); - selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + List selectedFieldNameList = List.of("result", "techFighter"); + List selectedMethodIdList = List.of("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); final FileTemplateCustomization customization = new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); doTest(fileTemplateConfig, customization); diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpockTest.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpockTest.java index 64c74b23..c7285b90 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpockTest.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorSpockTest.java @@ -51,11 +51,8 @@ public void testFileTemplateCustomization() { final TestMeConfig testMeConfig = new TestMeConfig(); testMeConfig.setOpenCustomizeTestDialog(true); final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); - List selectedFieldNameList = new ArrayList<>(); - selectedFieldNameList.add("result"); - selectedFieldNameList.add("techFighter"); - List selectedMethodIdList = new ArrayList<>(); - selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + List selectedFieldNameList = List.of("result", "techFighter"); + List selectedMethodIdList = List.of("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); final FileTemplateCustomization customization = new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); doTest(fileTemplateConfig, customization); diff --git a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestNgTest.java b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestNgTest.java index ca602204..5e9dbc6b 100644 --- a/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestNgTest.java +++ b/src/integrationTest/java/com/weirddev/testme/intellij/generator/TestMeGeneratorTestNgTest.java @@ -58,11 +58,8 @@ public void testFileTemplateCustomization() { final TestMeConfig testMeConfig = new TestMeConfig(); testMeConfig.setOpenCustomizeTestDialog(true); final FileTemplateConfig fileTemplateConfig = new FileTemplateConfig(testMeConfig); - List selectedFieldNameList = new ArrayList<>(); - selectedFieldNameList.add("result"); - selectedFieldNameList.add("techFighter"); - List selectedMethodIdList = new ArrayList<>(); - selectedMethodIdList.add("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); + List selectedFieldNameList = List.of("result", "techFighter"); + List selectedMethodIdList = List.of("com.example.services.impl.Foo#fight(com.example.foes.Fire,java.lang.String)"); final FileTemplateCustomization customization = new FileTemplateCustomization(selectedFieldNameList, selectedMethodIdList, true); doTest(fileTemplateConfig, customization); From 86a47abdda90b3971b2a8a4932f9e99ed9b60268 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Wed, 3 Apr 2024 11:54:15 +0800 Subject: [PATCH 35/38] Throw specific exceptions based on the method and configuration --- .../intellij/builder/MethodFactory.java | 28 +++++++++++-------- .../generator/TestTemplateContextBuilder.java | 2 +- .../intellij/template/TypeDictionary.java | 16 +++++++++-- .../context/TestMeTemplateParams.java | 2 ++ 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java b/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java index d1559122..4388e40a 100644 --- a/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java +++ b/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java @@ -57,7 +57,7 @@ public static Method createMethod(PsiMethod psiMethod, PsiClass srcClass, int ma Optional methodSubstitutor = findMethodSubstitutor(psiMethod, srcClass, ownerClassPsiType); Type returnType = resolveReturnType(psiMethod, maxRecursionDepth, typeDictionary, methodSubstitutor); List methodParams = extractMethodParams(psiMethod, isPrimaryConstructor, maxRecursionDepth, typeDictionary, methodSubstitutor); - String throwsExceptions = extractMethodExceptionTypes(psiMethod); + String throwsExceptions = extractMethodExceptionTypes(psiMethod,typeDictionary.isThrowSpecificExceptionTypes()); return new Method(methodId, methodName, returnType, ownerClassCanonicalType, methodParams, throwsExceptions,isPrivate, isProtected, isDefault, isPublic, isAbstract, isNative, isStatic, isSetter, isGetter, isConstructor, overriddenInChild, inherited, isInterface, syntheticMethod, propertyName1, accessible, isPrimaryConstructor, testable); @@ -173,20 +173,24 @@ private static List extractMethodParams(PsiMethod psiMethod, boolean shou //analyze the exception types of the method - private static String extractMethodExceptionTypes(PsiMethod psiMethod) { + private static String extractMethodExceptionTypes(PsiMethod psiMethod ,Boolean throwSpecificExceptionTypes) { String throwsExceptions = ""; - PsiReferenceList throwsList = psiMethod.getThrowsList(); - PsiClassType[] referencedTypes = throwsList.getReferencedTypes(); + if(throwSpecificExceptionTypes){ + PsiReferenceList throwsList = psiMethod.getThrowsList(); + PsiClassType[] referencedTypes = throwsList.getReferencedTypes(); - for (PsiClassType type : referencedTypes) { - PsiClass resolved = type.resolve(); - if (resolved != null) { - String exceptionTypeName = getExceptionTypeName(resolved.getQualifiedName()); - throwsExceptions += exceptionTypeName+","; + for (PsiClassType type : referencedTypes) { + PsiClass resolved = type.resolve(); + if (resolved != null) { + String exceptionTypeName = getExceptionTypeName(resolved.getQualifiedName()); + throwsExceptions += exceptionTypeName+","; + } } - } - if(StringUtils.isNotEmpty(throwsExceptions)){ - throwsExceptions = throwsExceptions.substring(0, throwsExceptions.length() - 1); + if(StringUtils.isNotEmpty(throwsExceptions)){ + throwsExceptions = throwsExceptions.substring(0, throwsExceptions.length() - 1); + } + }else{ + throwsExceptions = "Exception"; } return throwsExceptions; } diff --git a/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java b/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java index cc977c04..08a3884f 100644 --- a/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java +++ b/src/main/java/com/weirddev/testme/intellij/generator/TestTemplateContextBuilder.java @@ -47,7 +47,7 @@ public Map build(FileTemplateContext context, Properties default int maxRecursionDepth = context.getFileTemplateConfig().getMaxRecursionDepth(); ctxtParams.put(TestMeTemplateParams.MAX_RECURSION_DEPTH, maxRecursionDepth); ctxtParams.put(TestMeTemplateParams.StringUtils, new StringUtils()); - final TypeDictionary typeDictionary = TypeDictionary.create(context.getSrcClass(), context.getTargetPackage()); + final TypeDictionary typeDictionary = TypeDictionary.create(context.getSrcClass(), context.getTargetPackage(),context.getFileTemplateConfig().isThrowSpecificExceptionTypes()); JavaVersion javaVersion = getJavaVersion(context.getTestModule()); ctxtParams.put(TestMeTemplateParams.JAVA_VERSION, javaVersion); ctxtParams.put(TestMeTemplateParams.TestBuilder, new TestBuilderImpl(context.getLanguage(), context.getSrcModule(), typeDictionary, context.getFileTemplateConfig(), javaVersion)); diff --git a/src/main/java/com/weirddev/testme/intellij/template/TypeDictionary.java b/src/main/java/com/weirddev/testme/intellij/template/TypeDictionary.java index 521c5575..d46c5010 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/TypeDictionary.java +++ b/src/main/java/com/weirddev/testme/intellij/template/TypeDictionary.java @@ -35,8 +35,9 @@ public class TypeDictionary { private final List testSubjectMethodParamsType; private AtomicInteger newTypeCounter = new AtomicInteger(); private AtomicInteger existingTypeHitsCounter = new AtomicInteger(); + private boolean throwSpecificExceptionTypes; - private TypeDictionary(PsiClass srcClass, PsiPackage targetPackage, Set methodCallsFromTestSubject, List testSubjectMethodParamsType) { + private TypeDictionary(PsiClass srcClass, PsiPackage targetPackage, Set methodCallsFromTestSubject, List testSubjectMethodParamsType,boolean throwSpecificExceptionTypes) { this.testSubjectClass = srcClass; this.testSubjectTypesNames = resolveTypesNames(srcClass); this.targetPackage = targetPackage; @@ -44,6 +45,7 @@ private TypeDictionary(PsiClass srcClass, PsiPackage targetPackage, Set(MAX_RELEVANT_METHOD_IDS_CACHE); startTimestamp = System.currentTimeMillis(); + this.throwSpecificExceptionTypes = throwSpecificExceptionTypes; } private Set resolveTypesNames(PsiClass srcClass) { @@ -54,7 +56,7 @@ private Set resolveTypesNames(PsiClass srcClass) { return typesNames; } - public static TypeDictionary create(PsiClass srcClass, PsiPackage targetPackage){ + public static TypeDictionary create(PsiClass srcClass, PsiPackage targetPackage,boolean throwSpecificExceptionTypes){ Set methodCallsFromTestSubject = new HashSet<>(); if (srcClass != null) { for (PsiMethod method : srcClass.getAllMethods()) { @@ -64,7 +66,7 @@ public static TypeDictionary create(PsiClass srcClass, PsiPackage targetPackage) } } List testSubjectMethodParamsType = srcClass == null ? List.of() : Arrays.stream(srcClass.getAllMethods()).flatMap(psiMethod1 -> Arrays.stream(psiMethod1.getParameterList().getParameters()).map(p -> p.getType().getCanonicalText()).filter(TypeUtils::isBasicType)).toList(); - return new TypeDictionary(srcClass, targetPackage, methodCallsFromTestSubject, testSubjectMethodParamsType); + return new TypeDictionary(srcClass, targetPackage, methodCallsFromTestSubject, testSubjectMethodParamsType,throwSpecificExceptionTypes); } /** @@ -165,4 +167,12 @@ public void logStatistics() { LOG.info("**** Statistics: took %dms. type hits/req:%d/%d method relevancy cache %s".formatted( startTimestamp - System.currentTimeMillis(),newTypeCounter.get(), newTypeCounter.get() + existingTypeHitsCounter.get(), relevantMethodIdsCache.getUsageStats())); } + + public boolean isThrowSpecificExceptionTypes() { + return throwSpecificExceptionTypes; + } + + public void setThrowSpecificExceptionTypes(boolean throwSpecificExceptionTypes) { + this.throwSpecificExceptionTypes = throwSpecificExceptionTypes; + } } diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java b/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java index 0d5b9558..f8a46a2d 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/TestMeTemplateParams.java @@ -88,4 +88,6 @@ public interface TestMeTemplateParams { * Language of class under test: Groovy, Java, Scala */ String TESTED_CLASS_LANGUAGE = "TESTED_CLASS_LANGUAGE"; + + String THROW_SPECIFIC_EXCEPTION_TYPES = "throwSpecificExceptionTypes"; } From 0579e4fa3ebdd3522132b8e7b866540b6a46d09e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Wed, 3 Apr 2024 16:24:30 +0800 Subject: [PATCH 36/38] Throw specific exceptions based on the method and configuration --- .../intellij/builder/MethodFactory.java | 24 +++++++------------ .../intellij/template/context/Method.java | 9 ------- .../testMeTests/JUnit4 & Mockito.java.ft | 2 +- .../testMeTests/JUnit4 & Powermock.java.ft | 2 +- .../testMeTests/JUnit5 & Mockito.java.ft | 2 +- .../testMeTests/TestNG & Mockito.java.ft | 2 +- 6 files changed, 13 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java b/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java index 4388e40a..c169e2bd 100644 --- a/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java +++ b/src/main/java/com/weirddev/testme/intellij/builder/MethodFactory.java @@ -22,7 +22,6 @@ import com.weirddev.testme.intellij.utils.JavaPsiTreeUtils; import com.weirddev.testme.intellij.utils.PropertyUtils; import com.weirddev.testme.intellij.utils.TypeUtils; -import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -57,7 +56,7 @@ public static Method createMethod(PsiMethod psiMethod, PsiClass srcClass, int ma Optional methodSubstitutor = findMethodSubstitutor(psiMethod, srcClass, ownerClassPsiType); Type returnType = resolveReturnType(psiMethod, maxRecursionDepth, typeDictionary, methodSubstitutor); List methodParams = extractMethodParams(psiMethod, isPrimaryConstructor, maxRecursionDepth, typeDictionary, methodSubstitutor); - String throwsExceptions = extractMethodExceptionTypes(psiMethod,typeDictionary.isThrowSpecificExceptionTypes()); + String throwsExceptions = extractMethodExceptionTypes(psiMethod,typeDictionary.isThrowSpecificExceptionTypes(),testable); return new Method(methodId, methodName, returnType, ownerClassCanonicalType, methodParams, throwsExceptions,isPrivate, isProtected, isDefault, isPublic, isAbstract, isNative, isStatic, isSetter, isGetter, isConstructor, overriddenInChild, inherited, isInterface, syntheticMethod, propertyName1, accessible, isPrimaryConstructor, testable); @@ -173,8 +172,11 @@ private static List extractMethodParams(PsiMethod psiMethod, boolean shou //analyze the exception types of the method - private static String extractMethodExceptionTypes(PsiMethod psiMethod ,Boolean throwSpecificExceptionTypes) { - String throwsExceptions = ""; + private static String extractMethodExceptionTypes(PsiMethod psiMethod ,Boolean throwSpecificExceptionTypes,boolean testable) { + if(!testable){ + return null; + } + String throwsExceptions = null; if(throwSpecificExceptionTypes){ PsiReferenceList throwsList = psiMethod.getThrowsList(); PsiClassType[] referencedTypes = throwsList.getReferencedTypes(); @@ -182,11 +184,11 @@ private static String extractMethodExceptionTypes(PsiMethod psiMethod ,Boolean t for (PsiClassType type : referencedTypes) { PsiClass resolved = type.resolve(); if (resolved != null) { - String exceptionTypeName = getExceptionTypeName(resolved.getQualifiedName()); - throwsExceptions += exceptionTypeName+","; + String exceptionTypeName = resolved.getQualifiedName(); + throwsExceptions = throwsExceptions==null?exceptionTypeName+",":throwsExceptions +exceptionTypeName+","; } } - if(StringUtils.isNotEmpty(throwsExceptions)){ + if(throwsExceptions!=null){ throwsExceptions = throwsExceptions.substring(0, throwsExceptions.length() - 1); } }else{ @@ -194,14 +196,6 @@ private static String extractMethodExceptionTypes(PsiMethod psiMethod ,Boolean t } return throwsExceptions; } - - private static String getExceptionTypeName(String exceptionTypeName) { - int lastIndex = exceptionTypeName.lastIndexOf('.'); - return lastIndex != -1 ? exceptionTypeName.substring(lastIndex + 1) :exceptionTypeName; - } - - - private static ArrayList findMatchingFields(PsiParameter psiParameter, PsiMethod psiMethod) { final ArrayList fields = new ArrayList<>(); try { diff --git a/src/main/java/com/weirddev/testme/intellij/template/context/Method.java b/src/main/java/com/weirddev/testme/intellij/template/context/Method.java index 31f06fd5..498bad8b 100644 --- a/src/main/java/com/weirddev/testme/intellij/template/context/Method.java +++ b/src/main/java/com/weirddev/testme/intellij/template/context/Method.java @@ -156,14 +156,5 @@ public boolean hasReturn(){ public boolean hasParams() { return !methodParams.isEmpty(); } - - /** - * - * true - if method has Exception - */ - public boolean hasException(){ - return methodExceptionTypes != null && !methodExceptionTypes.trim().isEmpty(); - } - } diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft index b622356d..c0ef6ddb 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Mockito.java.ft @@ -29,7 +29,7 @@ public class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes#end { + public void #renderTestMethodName($method.name)()#if($method.methodExceptionTypes) throws $method.methodExceptionTypes#end { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft index 40f1f66e..995a2e0f 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit4 & Powermock.java.ft @@ -40,7 +40,7 @@ public class ${CLASS_NAME} { #foreach($method in $TESTED_CLASS.methods) #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes#end { + public void #renderTestMethodName($method.name)()#if($method.methodExceptionTypes) throws $method.methodExceptionTypes#end { #if($hasMocks && $PowerMockBuilder.shouldStub($method, $TESTED_CLASS)) #renderMockStubs($method, $TESTED_CLASS) #end diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft index 57cc16cd..d192988e 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft @@ -28,7 +28,7 @@ class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes#end { + void #renderTestMethodName($method.name)()#if($method.methodExceptionTypes) throws $method.methodExceptionTypes#end { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) diff --git a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft index 9eaf45e4..4c677e69 100644 --- a/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/TestNG & Mockito.java.ft @@ -28,7 +28,7 @@ public class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - public void #renderTestMethodName($method.name)()#if($method.hasException()) throws $method.methodExceptionTypes#end { + public void #renderTestMethodName($method.name)()#if($method.methodExceptionTypes) throws $method.methodExceptionTypes#end { #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS) From ce6047812a6a5781f24e8194dc72bfd00dd1e132 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Wed, 3 Apr 2024 16:40:57 +0800 Subject: [PATCH 37/38] Throw specific exceptions based on the method and configuration --- .../intellij/ui/settings/TestMeSettingsForm.form | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form index 598272d4..f6a38a11 100644 --- a/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form +++ b/src/main/java/com/weirddev/testme/intellij/ui/settings/TestMeSettingsForm.form @@ -13,7 +13,7 @@ - + @@ -50,6 +50,14 @@ + + + + + + + + From 3385ccfdf81b4d45e202b4736b10b6186d166957 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=97=E4=BA=AC-=E5=BC=A0=E5=87=A4=E6=9D=B0?= Date: Wed, 3 Apr 2024 17:05:54 +0800 Subject: [PATCH 38/38] Throw specific exceptions based on the method and configuration --- .../fileTemplates/testMeTests/JUnit5 & Mockito.java.ft | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft index d192988e..7744a90e 100644 --- a/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft +++ b/src/main/resources/fileTemplates/testMeTests/JUnit5 & Mockito.java.ft @@ -28,7 +28,7 @@ class ${CLASS_NAME} { #if($TestSubjectUtils.shouldBeTested($method)) @Test - void #renderTestMethodName($method.name)()#if($method.methodExceptionTypes) throws $method.methodExceptionTypes#end { + void #renderTestMethodName($method.name)(){ #if($hasMocks && $MockitoMockBuilder.shouldStub($method,$TESTED_CLASS)) #renderMockStubs($method,$TESTED_CLASS)