|
1 | 1 | package com.thealgorithms.maths.prime;
|
2 | 2 |
|
3 | 3 | import static org.junit.jupiter.api.Assertions.*;
|
| 4 | +import static org.mockito.ArgumentMatchers.any; |
4 | 5 |
|
5 | 6 | import com.thealgorithms.maths.Prime.EulerPseudoprime;
|
6 | 7 | import java.math.BigInteger;
|
7 | 8 | import org.junit.jupiter.api.Test;
|
| 9 | +import org.mockito.MockedStatic; |
| 10 | +import org.mockito.Mockito; |
8 | 11 |
|
9 | 12 | class EulerPseudoprimeTest {
|
10 | 13 |
|
@@ -75,8 +78,54 @@ void testUniformRandomRange() throws Exception {
|
75 | 78 | }
|
76 | 79 |
|
77 | 80 | @Test
|
78 |
| - void testCompositeWithZeroJacobiSymbol() { |
79 |
| - // Choose n = 9, a = 3 → jacobi(3,9) = 0 should make it return false early |
80 |
| - assertFalse(EulerPseudoprime.isProbablePrime(BigInteger.valueOf(9), 1)); |
| 81 | + void testIsProbablePrimeWhenJacobiSymbolIsZero() { |
| 82 | + try (MockedStatic<EulerPseudoprime> mockedPrimality = Mockito.mockStatic(EulerPseudoprime.class, Mockito.CALLS_REAL_METHODS)) { |
| 83 | + |
| 84 | + // Mock jacobiSymbol to return 0 to test the branch |
| 85 | + mockedPrimality.when(() -> EulerPseudoprime.jacobiSymbol(any(BigInteger.class), any(BigInteger.class))).thenReturn(0); |
| 86 | + |
| 87 | + boolean result = EulerPseudoprime.isProbablePrime(BigInteger.valueOf(15), 1); |
| 88 | + |
| 89 | + assertFalse(result); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + @Test |
| 94 | + void testJacobiSymbolThrowsForEvenOrNonPositiveN() throws Exception { |
| 95 | + var method = EulerPseudoprime.class.getDeclaredMethod("jacobiSymbol", BigInteger.class, BigInteger.class); |
| 96 | + method.setAccessible(true); |
| 97 | + |
| 98 | + // Helper lambda to unwrap InvocationTargetException |
| 99 | + Runnable invokeJacobi = () -> { |
| 100 | + try { |
| 101 | + method.invoke(null, BigInteger.valueOf(2), BigInteger.valueOf(8)); |
| 102 | + } catch (Exception e) { |
| 103 | + // unwrap |
| 104 | + Throwable cause = e.getCause(); |
| 105 | + if (cause instanceof IllegalArgumentException) { |
| 106 | + throw (IllegalArgumentException) cause; |
| 107 | + } else { |
| 108 | + throw new RuntimeException(e); |
| 109 | + } |
| 110 | + } |
| 111 | + }; |
| 112 | + |
| 113 | + // Now check that it actually throws |
| 114 | + assertThrows(IllegalArgumentException.class, invokeJacobi::run); |
| 115 | + |
| 116 | + // Another case: non-positive n |
| 117 | + Runnable invokeJacobi2 = () -> { |
| 118 | + try { |
| 119 | + method.invoke(null, BigInteger.valueOf(5), BigInteger.valueOf(-3)); |
| 120 | + } catch (Exception e) { |
| 121 | + Throwable cause = e.getCause(); |
| 122 | + if (cause instanceof IllegalArgumentException) { |
| 123 | + throw (IllegalArgumentException) cause; |
| 124 | + } else { |
| 125 | + throw new RuntimeException(e); |
| 126 | + } |
| 127 | + } |
| 128 | + }; |
| 129 | + assertThrows(IllegalArgumentException.class, invokeJacobi2::run); |
81 | 130 | }
|
82 | 131 | }
|
0 commit comments